HashSet In Java

In this tutorial, we will learn about HashSet in Java and how to use it.

HashSet implements Set Interface and it is backed by a HashMap. It is based on hashing principle and doesn’t maintain any order when you retrieve or iterate its object.

Some points to remember about HashSet in Java:

  • HashSet uses hashing principle to stores elements.
  • HashSet doesn’t allows duplicates. It contains unique elements only.
  • HashSet allows NULL value.
  • HashSet is non synchronized.
  • HashSet doesn’t maintain the insertion order.

HashSet is the best approach for search operations.

Creating HashSet in Java:

Let’s see how to create HashSet in Java:

HashSet<T> obj = new HashSet<>();

Here, “T” indicates the type of a HashSet. For example,

// create Integer type HashSet 
HashSet<Integer> obj = new HashSet<>(); 

// create String type HashSet 
HashSet<String> obj = new HashSet<>();

Default Capacity and Load Factor:

The initial default capacity of HashSet is 16, and the load factor is 0.75. Let’s see how to create HashSet using custom default capacity and load factor:

// HashSet with 8 capacity and 0.5 load factor 
HashSet<Integer> numbers = new HashSet<>(8, 0.5f);

Notice, the part new HashSet<>(8, 0.5f). Here, the first parameter is capacity, and the second parameter is the load factor.

  • Capacity – It defines the capacity to store elements. Meaning, it can store 8 elements.
  • LoadFactor – It defines at what level the HashMap capacity should be doubled. Meaning, whenever our hash set is filled by 50%, a new hashmap will be created and elements will be copied to it.

If you didn’t mention capacity and load factor then default values will be used.

HashSet Declaration:

Below is the java.util.HashSet class declaration present in the JDK:

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable {
    private transient HashMap<E, Object> map;

    public HashSet() {
        this.map = new HashMap();
    .... rest methods

Java HashSet Example

Let’s see a simple example of HashSet.

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> obj = new HashSet<>();

        // adding elements

        System.out.println("Values --> " + obj);

        // removing element

        System.out.println("Values After Removing--> " + obj);


Values --> [Apple, Grapes, Mango, Banana]
Values After Removing--> [Grapes, Mango, Banana]

As you can see, duplicate values are not allowed and insertion order is also not maintained.

Note: HashSet is not synchronized. Meaning, if you’re working in a multi-threaded environment then HashSet will not be the best fit. Instead, you’ve to use some thread-safe hashmap based collection or synchronize HashSet externally.

Set s = Collections.synchronizedSet(new HashSet(...));

Official Docs: Read Here

ArrayDeque Class in Java

LinkedHashSet in Java

Leave a Comment