12

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?

my name is GYAN
  • 1,269
  • 13
  • 27
  • The iteration ordering method for linked hash map: `true` for access-order, `false` for insertion-order. – DimaSan Aug 16 '16 at 12:04
  • 1
    It's described, nay, specified, in the [Javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html). What part of that didn't you understand? – user207421 Aug 16 '16 at 12:31

2 Answers2

20

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
OLIVER.KOO
  • 5,654
  • 3
  • 30
  • 62
Eran
  • 387,369
  • 54
  • 702
  • 768
3

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.

AmanSinghal
  • 2,404
  • 21
  • 22