In the previous tutorials, we have discussed what is HashSet and Tree Set with customizable sorting. Now we are going to discuss LinkedHashSet.
What is LinkedHashSet?
LinkedHashSet is a child class of HashSet, which was introduced at Java 1.4 Version. The underlying data structure is the combination of HashTable and LinkedList, hence it is termed as LinkedHashSet then it doesn’t allow the duplicates, and it will maintain the insertion order.
LinkedHashSet = HashTable+LinkedList
The main difference between the HashSet and Linked Hash Set is, the Linked Hash Set maintain the insertion order, where HashSet doesn’t maintain insertion order.
Example Of LinkedHashSet
public class LinkedHashSetDemo {
public static void main(String[] args) {
LinkedHashSet lhs = new LinkedHashSet();
lhs.add("P");
lhs.add(null);
lhs.add("A");
lhs.add("p");
lhs.add(0);
lhs.add("z");
System.out.println("Elements : "+lhs);
}
}
Elements : [P, null, A, p, 0, z]
On the above example, we can see the output with insertion order.
When we should go with LinkedHashSet
If we want to store a group of objects in a collection, where duplicates are not allowed and insertion order is maintained, then we go with the Linked Hash Set.
Key points
- The underlying data structure for Linked Hash Set is HashTable and LinkedList.
- In Linked Hash Set duplicate elements are not allowed.
- While iterating the Linked HashSet,we can expect the elements, according to our insertion order.
- Linked Hash Set allows the heterogeneous elements.
Happy Learning 🙂