javalinkedhashmapinsertion-order

Does a collection (values) from LinkedHashMap preserve the insertion order?


Let's say I have a LinkedHashMap<String, Double> myMap which I added pair1, pair2, pair3 pairs to.

And now I do the following loop :

for (Double currDouble : myMap.getValues()) {...}

Would the First Double object in the loop be the one of pair1? And second of pair2? Or it doesn't have to be?

I checked with similar program and It seems that it does keep insertion order, but Would that always be the case?


Solution

  • Yes!

    From the first sentence of the LinkedHashMap documentation: ... implementation of the Map interface, with predictable iteration order.... which is normally the order in which keys were inserted into the map (insertion-order).

    If a key is reinserted ( possibly with a different value ) it doesn't change the original order.