10

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,

Manish
  • 1,274
  • 3
  • 22
  • 59

1 Answers1

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

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 1
    Thanks for explanation. So the javadoc statement was for "insertion-ordered" map that order is not affected on reinserting the key. – Manish Mar 07 '16 at 08:38
  • Thanks for the quote! Was having a hard time finding it explicitly stated in the docs. – Kun May 09 '21 at 01:59