LinkedHashSet in java is part of the Collection framework. It implements the Set interface and extends the HashSet class.
LinkedHashSet maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, hence the LinkedHashSet maintains the insertion order of elements.
Few points to remember about LinkedHashSet
1. Similar to HashSet, it only allows unique elements
2. Allows one null
3. Maintains insertion order of elements
4. Is non Synchronized.
How LinkedHashSet in java works internally
As earlier stated, LinkedHashSet extends HashSet, and all the constructors that LinkedHashSet has call the HashSet constructor HashSet(int initialCapacity, float loadFactor, boolean dummy). This HashSet constructor internally calls LinkedHashMap
1 2 3 |
HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); } |
So LinkedHashSet internally uses LinkedHashMap for storing the elements.
We will see how LinkedHashMap internally works in our coming posts.
LinkedHashSet doesnt have any own implementations of any of the Set methods, hence all the methods of HashSet work exactly same in LinkedHashSet with only difference is preserving insertion order.
Constructors
LinkedHashSet()
Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
LinkedHashSet(Collection extends E> c)
Constructs a new linked hash set with the same elements as the specified collection.
LinkedHashSet(int initialCapacity)
Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).
LinkedHashSet(int initialCapacity, float loadFactor)
Constructs a new, empty linked hash set with the specified initial capacity and load factor.