In Java LinkedHashSet is created with backing HashSet creating LinkedHashMap with following LinkedHashMap constructor
map = new LinkedHashMap<>(initialCapacity, loadFactor);
Now in LinkedHashMap, the above constructor in turn calls
public LinkedHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
accessOrder = false;
}
so is there any way to have a LinkedHashSet with accessOrder
set to true
?
This can help create LRU cache implementation with LinkedHashSet.
Java LinkedHashSet class contains unique elements only like HashSet. Java LinkedHashSet class provides all optional set operations and permits null elements. Java LinkedHashSet class is non-synchronized. Java LinkedHashSet class maintains insertion order.
HashSet is an unordered & unsorted collection of the data set, whereas the LinkedHashSet is an ordered and sorted collection of HashSet. HashSet does not provide any method to maintain the insertion order. Comparatively, LinkedHashSet maintains the insertion order of the elements.
The performance of HashSet is better when compared to LinkedHashSet and TreeSet. TreeSet performance is better than LinkedHashSet except for insertion and removal operations because it has to sort the elements after each insertion and removal operation.
In a set, no duplicates are allowed. Every element in a set must be unique. We can simply add elements to a set, and finally we will get a set of elements with duplicates removed automatically. HashSet, LinkedHashSet and TreeSet are the implementations of Set interface which does not allow duplicate elements.
LinkedHashSet
doesn't support access order, since you are not accessing elements of a LinkedHashSet
.
You add elements to the LinkedHashSet
, and you can iterate over them in insertion order.
When you check if an element is a member of the LinkedHashSet
, you are not accessing it. You check membership via boolean contains(Object o)
, calls map.containsKey(o)
for the backing map. However, containsKey()
doesn't affect the access order of the Map
.
On the other hand, the get(Object key)
method of LinkedHashMap
does affect access order, but it is never used by LinkedHashSet
.
As you can see from the source code, a LinkedHashSet is backed by a LinkedHashMap with the accessOrder set to false.
Furthermore, there is no public constructor for LinkedHashSet to change the access order from insertion order to access order.
You could try this (just an example):
LinkedHashSet<E> set = (LinkedHashSet<E>) Collections.newSetFromMap(new LinkedHashMap<>(16, 0.75f, true));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With