HashSet overview
HashSet is a java class which implements Set interface
Main features of HashSet
HashSet contains only unique elements, does not allow duplicates.
HashSet stores elements by using “hashing” mechanism
It does not maintain the insertion order, elements will be in random order.
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 HashSet using constructor as below
- HashSet<String> hs = new HashSet<String>();
HashSet<String> hs = new HashSet<String>();
Example :
- import java.util.HashSet;
- public class HashSetExample {
- public static void main(String args[]) {
- HashSet<String> hs = new HashSet<String>();
- hs.add("java");
- hs.add("c");
- hs.add("c++");
- //Adding duplicate elements
- hs.add("java");
- hs.add("c++");
- //Adding null values
- hs.add(null);
- hs.add(null);
- //Displaying HashSet elements
- System.out.println(hs);
- }
- }
import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { HashSet<String> hs = new HashSet<String>(); hs.add("java"); hs.add("c"); hs.add("c++"); //Adding duplicate elements hs.add("java"); hs.add("c++"); //Adding null values hs.add(null); hs.add(null); //Displaying HashSet elements System.out.println(hs); } }
Note : We can observe in the output that, duplicate elements are not present including Null duplicate value.
When to use HashSet ?
HashSet should be used whenever We want to store only unique elements in a collection and We are not interested to maintain the order of insertion
When not use HashSet ?
HashSet should not be used whenever We need to allow duplicate elements and We need to maintain the insertion order within the collection