Home > OS >  Does HashMap keeps its order (not insertion order)
Does HashMap keeps its order (not insertion order)

Time:02-23

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.

CodePudding user response:

Yes. It will keep its order if no new items are added. An idle map does not just decide to rearrange itself. But that order is non deterministic and can change once items are added.

CodePudding user response:

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.

  • Related