5

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

codeMan
  • 5,730
  • 3
  • 27
  • 51

2 Answers2

13

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 map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

tom
  • 21,844
  • 6
  • 43
  • 36
1

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.

Shyam
  • 6,376
  • 1
  • 24
  • 38