In LinkedHashMap, Does insertion order change with re-insertion when accessOrder is true

Swarup Ranjan Sahoo :

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}
    }
 }
Swarup Ranjan Sahoo :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=125708&siteId=1