Why does LinkedHashSet have a boolean accessOrder set to false

In Java, a LinkedHashSet is created with HashSet support, creating a LinkedHashMap with the following LinkedHashMap constructor

map = new LinkedHashMap<>(initialCapacity, loadFactor); 

Now in LinkedHashMap the above constructor calls

  public LinkedHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); accessOrder = false; } 

is there any way to set LinkedHashSet with accessOrder to true ? This can help create an LRU cache implementation using LinkedHashSet.

+5
source share
2 answers

LinkedHashSet does not support access order because you are not accessing LinkedHashSet elements.

You add items to the LinkedHashSet , and you can LinkedHashSet over them in order of placement.

When you check if an item is a member of a LinkedHashSet , you are not accessing it. You check membership through boolean contains(Object o) , calls map.containsKey(o) for the support map. However, containsKey() does not affect the Map access order.

On the other hand, the LinkedHashMap get(Object key) LinkedHashMap affects the access order, but it is never used by LinkedHashSet .

+4
source

As you can see from the source code, LinkedHashSet is supported by LinkedHashMap with the accessOrder parameter set to false.

In addition, there is no public constructor for LinkedHashSet to change the access order from the insertion order for access.

You can try this (just an example):

 LinkedHashSet<E> set = (LinkedHashSet<E>) Collections.newSetFromMap(new LinkedHashMap<>(16, 0.75f, true)); 
0
source

Source: https://habr.com/ru/post/1273922/


All Articles