The following field in used in LinkedHashMap.java:
final boolean accessOrder;
LinkedHashMap has a constructor which sets this field:
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
I want to know purpose of the accessOrder field. Please give an example which differentiate if accessOrder is true and false. Is there any other way to update the accessOrder field of an already created object?
The entries of a LinkedHashMap can be iterated either in the order the keys were first added to the Map (that's the default behavior) or according to access order (i.e. the most recently accessed entry will be the last entry iterated over).
By passing true to the accessOrder parameter in that constructor, you are saying you wish to iterate over the entries according to access order (and not insertion order).
Map<Integer,String> insertOrder = new LinkedHashMap<>(16,0.75f,false);
Map<Integer,String> accessOrder = new LinkedHashMap<>(16,0.75f,true);
insertOrder.put (1,"a");
insertOrder.put (3,"c");
insertOrder.put (2,"b");
String v = insertOrder.get(3);
accessOrder.put (1,"a");
accessOrder.put (3,"c");
accessOrder.put (2,"b");
v = accessOrder.get(3);
System.out.println(insertOrder);
System.out.println(accessOrder);
Output :
{1=a, 3=c, 2=b} // the last inserted key (2) is last
{1=a, 2=b, 3=c} // the most recently accessed key (3) is last