LinkedHashSet overview
LinkedHashSet is an implementation of Set interface in java
Important features of LinkedHashSet
It contains only unique elements, does not allow duplicates
LinkedHashSet stores elements by using “hashing” mechanism
It maintains the insertion order, elements will be stored in the same order as we insert
It allows null value, since it allows unique values, only one null value is allowed
It is non-synchronized Set by default, however we can synchronize it using Collections utility
We can create LinkedHashSet using constructor as below
- LinkedHashSet lhs = new LinkedHashSet();
LinkedHashSet lhs = new LinkedHashSet();
Example :
- import java.util.*;
- public class LinkedHashSetExample {
- public static void main(String args[]) {
- LinkedHashSet<String> lhs = new LinkedHashSet<String>();
- lhs.add("java");
- lhs.add("c");
- lhs.add("c++");
- //Adding duplicate elements
- lhs.add("java");
- lhs.add("c++");
- //Adding null values
- lhs.add(null);
- lhs.add(null);
- //Displaying HashSet elements
- System.out.println(lhs);
- }
- }
import java.util.*; public class LinkedHashSetExample { public static void main(String args[]) { LinkedHashSet<String> lhs = new LinkedHashSet<String>(); lhs.add("java"); lhs.add("c"); lhs.add("c++"); //Adding duplicate elements lhs.add("java"); lhs.add("c++"); //Adding null values lhs.add(null); lhs.add(null); //Displaying HashSet elements System.out.println(lhs); } }
Note : We can observe in output, that duplicate elements are not present including Null duplicate value and also insertion order is maintained
When to use LinkedHashSet ?
LinkedHashSet should be used whenever we want to store only unique elements in a collection and we are interested to maintain the order of insertion
When not use LinkedHashSet ?
LinkedHashSet should not be used whenever we need to allow duplicate elements and insertion order is not important