'Does HashMap keeps its order (not insertion order)

Sorry if and answer to this is out there. I just could not find it. I don't care about insertion order, I just want to ensure that HashMap keeps its order without any puts being used in between.

If I have the following code:

StringBuilder keyChecker = new StringBuilder("");
for(String field : hashmap().keySet()){
    keyChecker.append(field).append(",");
}

for(String field : hashmap().keySet()){
    setAny(checker,x++, hashmap().get(field) );
    x++;
}

Will the (1st,2nd,3rd,etc) field always match the same one next time I call HashMap keyset.

From my tests it seems like it always does, but I am not sure about any edge cases that I may come across.



Solution 1:[1]

WJS is correct. That said, it is very bad style to depend on this. If you actually depend on the order of the entries, I would suggest using a TreeMap or one of the Apache Commons implementations of OrderedMap.

You might be able to get by with your assumption that the order will be stable right now ... but if another developer works on the code, that assumption might not be known and the code will break in unexpected ways that will be big headache for somebody to solve.

If you depend on entry order, use a data structure that guarantees that order.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steve