When iterating through a HashMap with Integer keys, will it always return keys in ascending order?

家住魔仙堡 提交于 2019-12-12 03:44:34

问题


I have a HashMap defined as such:

public Map<Integer, String> staticBlockPositions = new HashMap<Integer, String>();

I am iterating over the map by getting each key, like this:

for (Integer key : blockPositions.keySet()) {
    System.out.println(key);
}

My question is, can I rely on the value of key to always be in ascending order. So if my HashMap looks something like this:

{
    4: "abc123",
    1: "def456",
    11: "qwe789",
    10: "iop019"
}

(I know this is JSON format, this is just so you get an idea of the data set).

Will my loop always output

1
4
10
11

regardless of the order of my data?

Important to note, the order in which the keys are add is completely random, and I cannot control what key is added when.

This is for a Tetris style game, so getting the keys in ascending order is a must.


回答1:


Quoting 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.

There is no special case for integer keys. You simply can't rely upon the order.

If you want the keys to be in ascending order, use an implementation of SortedMap, like TreeMap.




回答2:


In addition to what @AndyTurner stated about HashMap not guaranteeing order, it appears that TreeMap provides the functionality you are looking for.




回答3:


No,

  1. To maintain sorted order, use TreeMap.

  2. To maintain insertion order, use LinkedHashMap.



来源:https://stackoverflow.com/questions/43187629/when-iterating-through-a-hashmap-with-integer-keys-will-it-always-return-keys-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!