HashSet in java
HashSet stores only unique elements. No duplicates are allowed unlike List. Below is the hierarchy of Set interface in collections framework

HashSet
One of the implementation class of Set interface is HashSet. It stores elements using a mechanism called hashing. Below are some important features of hash set.
- Stores only unique elements
- Uses hashing technique to store elements
- It allows one null value
- Doesn’t maintain insertion order of elements
- elements are stored according to their hash codes
- Initial capacity is 16 with load factor 0.75
Creating and iterating over HashSet
In the below example, we are adding some duplicate elements, but hash set will keep only a single copy of duplicate element.
package com.javatrainingschool;
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
Set<Integer> set = new HashSet<Integer>();
set.add(100);
set.add(300);
set.add(400);
set.add(300);
set.add(500);
set.add(500);
System.out.println("Size of the set is : " + set.size());
for(int value : set) {
System.out.println(value);
}
}
}
Output :
Size of the set is : 4
400
100
500
300
Remove methods in Set
//Below method will remove the specified object
public boolean remove(Object o);
boolean removeAll(Collection<?> c);
//Below method will clear the HashSet
public void clear();
Contains method in HashSet
This method checks if the passed object exist in the hashset or not. Below is the syntax
public boolean contains(Object o);