I have a fixed set of key value pairs with which I am initializing the LinkedHashMap<String, Double>.
Does the insertion order remain the same when I do a
LinkedHashMap.put(existingKey, newValue);
To be precise my question is, when we update a value for a key using the put
method, is the order of initial insertion disturbed??
If so 1) why? 2) How can I prevent this to preserve the initial order of insertion?
I chose LinkedHashMap because, I wanted a collection that supports a key value pair and maintains the the insertion order.
TIA
From the class doc:
Note that insertion order is not affected if a key is re-inserted into the map. (A key
k
is reinserted into a mapm
ifm.put(k, v)
is invoked whenm.containsKey(k)
would returntrue
immediately prior to the invocation.)
This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
So, yes, keySet(), values(), and entrySet() (the three collection views mentioned) return values in the order the internal linked list uses. And yes, the JavaDoc for Map and LinkedHashMap guarantee it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With