Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is purpose of 'accessOrder' field in LinkedHashMap?

There is a field in used by LinkedHashMap.java is:

final boolean accessOrder;

A constructor of LinkedHashMap is:

public LinkedHashMap(int initialCapacity,
                         float loadFactor,
                         boolean accessOrder) {
        super(initialCapacity, loadFactor);
        this.accessOrder = accessOrder;
    }

I want to know purpose of the field accessOrder. Please give an example which differentiate if accessOrder is 'true and 'false'. Is there any other way to to update the accessOrder field of a already created object?

like image 596
my name is GYAN Avatar asked Aug 16 '16 12:08

my name is GYAN


2 Answers

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
like image 133
Eran Avatar answered Oct 19 '22 15:10

Eran


The constructor which is used to create the access ordered LinkedHashMap, is as follow:

LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)

Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and accessOrder.

if accessOrder is false, then it will result in insertion order.

if accessOrder is true, then it will result in access Order. One of the important application of access order LinkedHashMap is building LRU cache.

like image 3
AmanSinghal Avatar answered Oct 19 '22 14:10

AmanSinghal