java在使用整数键遍历HashMap时,是否总是以升序返回键?
我有一个定义如下的HashMap:
public Map<Integer, String> staticBlockPositions = new HashMap<Integer, String>();
我通过获取每个关键点在地图上迭代,如下所示:
for (Integer key : blockPositions.keySet()) {
System.out.println(key);
}
我的问题是,我是否可以依赖key
的值始终以升序排列。因此,如果我的HashMap看起来像这样:
{
4: "abc123",
1: "def456",
11: "qwe789",
10: "iop019"
}
(我知道这是JSON格式,这只是为了让您了解数据集)
我的循环是否总是输出
1
4
10
11
不管我的数据顺序如何
重要的是要注意,添加键的顺序是完全随机的,我无法控制何时添加哪个键强>
这是一款俄罗斯方块风格的游戏,因此按升序获得钥匙是一项必须的任务
# 1 楼答案
不
要保持排序顺序,请使用树形图
要保持插入顺序,请使用LinkedHashMap
# 2 楼答案
引用the Javadoc
整数键没有特殊情况。你根本不能依赖订单
如果希望键按升序排列,请使用}
SortedMap
的实现,如^{# 3 楼答案
除了@AndyTurner所说的
HashMap
不能保证秩序之外,似乎TreeMap还提供了您想要的功能