Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens if we 'put' and new value to an already existing key in the Linkedhashmap

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

like image 739
codeMan Avatar asked Jan 17 '14 07:01

codeMan


2 Answers

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.)

like image 144
tom Avatar answered Oct 01 '22 14:10

tom


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.

like image 28
sachin10 Avatar answered Oct 01 '22 14:10

sachin10