As specified in the javadoc for LinkedHashMap, insertion order is not affected if a key is re-inserted into the map but While running the below program,I notice that inserting the same key again in changing the access order.
Map<Integer, String> map = new LinkedHashMap<Integer,String>(16, .75f, true);
map.put(new Integer(1), "Ajay");
map.put(new Integer(2), "Vijay");
map.put(new Integer(3), "Kiran");
map.put(new Integer(4), "Faiz");
for(String value:map.values()){
System.out.println(value);
}
String val =map.get(new Integer(3));
map.put(new Integer(2), "Ravi");
System.out.println("After changes...");
for(String value:map.values()){
System.out.println(value);
}
On Running the above program i am getting the o/p as follows:
Ajay
Vijay
Kiran
Faiz
After changes...
Ajay
Faiz
Kiran
Ravi
when i reinsert the key 2 using, why it's access order is changed.
Please help me to understand the o/p.
Thanks,
new LinkedHashMap<Integer,String>(16, .75f, true);
With that true
you specify that you want an "access-ordered" map, not an "insertion-ordered" map.
This means that you will get the values in the order of access (least recently accessed first).
Both your get
and put
calls constitute an "access".
A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches. Invoking the put or get method results in an access to the corresponding entry (assuming it exists after the invocation completes).
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