Core Java

HashSet In Java


HashSet in Java implements Set interface i.e. it doesn’t allow duplicates. It is internally backed by a HashMap which works on the principle of hashing. 

We can store a null value in a HashSet. Its default capacity is 16 with a load factor of 0.75, where:

A Java HashSet is non-synchronized. Also, there’s no guarantee to retain the insertion order of elements.

In this tutorial, we’ll learn how to work with a Java HashSet.

Instantiating HashSet:

We can create a Java HashSet using one of the following constructors:

Each of these constructor usages is pretty intuitive.

Let’s quickly create a HashSet using the default constructor:

Commonly Used Methods:

Let’s now look at some methods that can help us manipulate over a Java HashSet:

1. boolean add(E e):

It simply adds an element to the given set, if not present already. If the element is already present, add() simply returns false:

2. boolean contains(Object obj):

The contains() method returns true if the element exists in the referenced set, false otherwise:

3. boolean remove(Object obj):

As the name suggests, it removes the element obj if it exists and returns true. If no such element exists, it simply returns false:

Note that the HashSet also inherits removeAll() and removeIf() methods, which can be used to remove values.

4. boolean isEmpty():

It returns true for an empty set, false otherwise:

5. int size():

It simply returns the number of elements present in the given set.

6. void clear():

The clear() method removes all values present in the referenced set, thereby making it an empty set.

Internal Implementation:

A HashSet internally uses a HashMap to store its elements. The elements stored in a HashSet are mapped as the keys in a HashMap. The value fields of all these entries contain a constant PRESENT:

which is a dummy object.

Iterating Over HashSet:

We can use one of the following ways to iterate over the elements in a HashSet:

1. forEach():

Java 8 onwards, we can use forEach() to iterate over any Java Collection:

2. forEachRemaining():

Java 8 also supports forEachRemaining() construct to be used with any iterator over a Collection:

3. Iterate Using Iterator:

In case we’re on a Java 7 or lower versions, we can simply iterate through using an iterator:

4. Extended for Loop:

We can also use an extended for loop to traverse through the elements:


In this tutorial, we learned how to create and work with a Java HashSet. We also know that the Java HashSet internally uses a HashMap for its implementation.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *