问题
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,
To maintain sorted order, use TreeMap.
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