LinkedHashSet
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
- We can observe the result is in order of insertion.