4

In LinkedHashMap

Note 1. "Insertion order is not affected if a key is re-inserted into the map."

Note 2. "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)."

Query:

  1. Does re-insertion (put method) modify recent access of that specified entry object or it is only get method which alters the recent access?
  2. If accessOrder is true while constructing a LinkedHashMap, does "Note 1" statement above get contradicted and insertion order is affected?

Update

As per below test code, both put and get method changing access order. Then is Note 1 apparently not correct with accessOrder = true in LinkedHashMap constructor.

 public class Main
 {
    public static void main(String[] args) {

        LinkedHashMap<Integer, String> map = new LinkedHashMap<>(16, .75f, true);
        map.put(1, "A");
        map.put(2, "B");
        map.put(3, "C");
        map.put(4, "D");
        map.put(5, "E");
        System.out.println(map);// Output: {1=A, 2=B, 3=C, 4=D, 5=E}

        // get method changed access order
        String dummy = map.get(2);
        System.out.println(map);  // Output: {1=A, 3=C, 4=D, 5=E, 2=B}

        // put method changed access order
        map.put(1, "Z");
        System.out.println(map);  // Output: {3=C, 4=D, 5=E, 2=B, 1=Z}
    }
 }
  • 4
    You could easily setup a small demo code on your own to test point #1. – Tim Biegeleisen Jul 25 '19 at 16:11
  • Updated with test case, Second query is prime concern, query 1 is mere validation for query 2 – SwarupRanjanSahoo Jul 25 '19 at 17:31
  • "*Does insertion order change with re-insertion when accessOrder is true*" doesn't really make sense. When we set `accessOrder` to `true` we are changing ordering of all entries in that `LinkedHashMap` from time of insertion to time of accessing. So since there is no more *insertion order* in use it can't be affected (unless I misunderstood your question). – Pshemo Jul 25 '19 at 19:54
  • Yes, it was little confusing at the beginning that with `accessOrder` being `true` we are setting a new ordering, and it's not as per insertion order anymore exactly which I have posted in answer already before your comment. Thanks though – SwarupRanjanSahoo Jul 26 '19 at 06:55

1 Answers1

0

Insertion order does not change when a mapping is reinserted or updated by put method. Both these following line as per example above will change access order but not insertion order.

map.put(1,"A");
map.put(1,"Z");

Access order, with accessOrder = true would change as per least recent access to most recent access, that is

{2=B, 3=C, 4=D, 5=E, 1=A}
{2=B, 3=C, 4=D, 5=E, 1=Z}

But Insertion order is still the same, which can be printed with accessOrder = false, that is

{1=A, 2=B, 3=C, 4=D, 5=E}

So, insertion order is not changed with reinsertion, but access order changes in a LinkedHashMap.