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:
- Does re-insertion (
put
method) modify recent access of that specified entry object or it is onlyget
method which alters the recent access? - If
accessOrder
istrue
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}
}
}
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.