LinkedHashSet
LinkedHashSet is a subclass of HashSet and implements the Set interface in Java. It is part of the Java.util package and is used to store unique elements while maintaining insertion order.
Features of LinkedHashSet
- LinkedHashSet is the subclass of the HashSet class.
- It is implemented by using the hybrid data structure LinkedList and HashTable.
- It maintains the order of insertion.
- The default capacity of LinkedHashMap is 16 and it grows based on the load factor or fill ratio i.e. 0.75
- The Hashtable structure is used for the unique storage of elements whereas LinkedList is used to preserve the insertion order.
- The main difference between HashSet and LinkedhashSet is that HashSet doesn't maintain the insertion order of insertion, and LinkedHashset maintains the order. Let's see one example of how the Linkedhashset works.
Example:
package com.quipoin;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class Employee {
public static void main(String[] args) {
LinkedHashSet<String> lh=new LinkedHashSet<>();
lh.add("Vivek");
lh.add("Atul");
lh.add("Prince");
lh.add("Prashant");
lh.add("Naveen");
Iterator<String> itr=lh.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.println(str);
}
}
}
Output:
Vivek
Atul
Prince
Prashant
Naveen
Explanation
- The elements are inserted in the same order as they were added.
- In HashSet, insertion order is maintained, But in LinkedHashSet insertion order is maintained.
Difference Between HashSet and LinkedHashSet
Feature | HashSet | LinkedHashSet |
---|---|---|
Maintains Order | No | Yes |
Underlying DS | HashTable | HashTable + LinkedList |
Performance | Slightly Faster | Slightly Slower (due to extra LinkedList overhead) |
Use Case | When order is not important | When insertion order need to be preserved |