我有一个 HashMap 定义如下:
public Map<Integer, String> staticBlockPositions = new HashMap<Integer, String>();
我通过获取每个键来迭代 map ,如下所示:
for (Integer key : blockPositions.keySet()) {
System.out.println(key);
}
我的问题是,我可以依靠 key
的值始终按升序排列吗?所以如果我的 HashMap 看起来像这样:
{
4: "abc123",
1: "def456",
11: "qwe789",
10: "iop019"
}
(我知道这是 JSON 格式,这只是为了让您了解数据集)。
我的循环总是输出
1
4
10
11
不管我的数据顺序如何?
重要的是要注意,添加 key 的顺序完全是随机的,我无法控制何时添加什么 key 。
这是俄罗斯方 block 风格的游戏,因此按升序排列按键是必须。
最佳答案
引用the Javadoc :
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
整数键没有特殊情况。您根本不能依赖该订单。
如果您希望键按升序排列,请使用 SortedMap
的实现,例如 TreeMap
.
关于java - 当使用 Integer 键迭代 HashMap 时,它总是按升序返回键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43187629/