Java Collection Framework provides a set of interfaces and implemented classes. The HashSet in Java is a direct implementation of the Set interface, which provides the functionality to store the collection of Objects.
HashSet in Java
The underlying data structure of the HashSet is a Hash Map. When we create a HashSet Object, It internally creates a new empty Set with the backing HashMap instance.
The HashMaps’s initial capacity is 16, and the load factor is 0.75.
Source code for HashSet constructor.
public HashSet() {
map = new HashMap<E, Object>();
}
Usually, Hash Map is a Collection, which stores the data as key-value pairs. But in the HashSet, we are going to insert only values by using the add() method. When we add value to HashSet, the add() method internally put the given value as a key in the underlying hash map and assign the dummy object as a value, hence the HashSet doesn’t allow the duplicate values.
Below is the add() method source code for understanding.
public Boolean add(E e) {
return map.put(e, dummy_object) == null;
}
Example:
public class HashSetDemo {
public static void main(String[] args) {
Set set = new java.util.HashSet();
set.add("X");
set.add("Y");
set.add("Z");
set.add("A");
set.add(2);
set.add(null);
System.out.println("set : " + set);
}
}
Output:
Values : [null, 2, A, Y, X, Z]
On the above output, if we observe closely, the insertion order is not the same. The Hash Set doesn’t guarantee the insertion order. Based on the hash code of the values, the order is confirmed.
Key Points
- Hash Set doesn’t allow duplicate values.
- Hash Set doesn’t maintain insertion order.
- Hash Set accepts the various data elements.
- The initial capacity of the Hash Set is 16.
- The load factor of Hash Set is 0.75.
- Hash Set is recommended to repeated CRUD operations.
Trying to add the duplicate element in HashSet
When we try to insert a duplicate item to HashSet, it doesn’t throw any exception or error.
In the case of a duplicate, insertion add() method returns the “false”.
Example:
public class HashSetDemo {
public static void main(String[] args) {
Set set = new java.util.HashSet();
set.add("X");
set.add("Y");
set.add("Z");
set.add("A");
set.add(2);
set.add(null);
System.out.println("is allow duplicates. ? " + set.add("Y"));
System.out.println("Values : " + set);
}
}
Output:
is allow duplicates. ? false
Values : [null, A, 2, X, Y, Z]
Happy Learning 🙂