Java HashSet
HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn’t maintain any specific order of elements.
- Can store the Null values.
- Uses HashTable internally.
- Also implements Serializable and Cloneable interfaces.
- HashSet is not thread-safe. So to make it thread-safe, synchronization needed externally.
Example:
// Java program to show the use of HashSet
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args) {
// Instantiate an object of HashSet
HashSet<Integer> hs = new HashSet<>();
hs.add(1);
hs.add(2);
hs.add(1);
// Printing the Size and Element of HashSet
System.out.println("HashSet Size: " + hs.size());
System.out.println("Elements in HashSet: " + hs);
}
}
Output
HashSet Size: 2 Elements in HashSet: [1, 2]
For a more in-depth understanding of HashSet and its applications, the Java Programming Course offers detailed lessons on sets and other Java Collections.
Declaring a HashSet in Java
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
where E is the type of elements stored in a HashSet.
Before storing an Object, HashSet checks whether there is an existing entry using hashCode() and equals() methods. In the above example, two lists are considered equal if they have the same elements in the same order. When you invoke the hashCode() method on the two lists, they both would give the same hash since they are equal.
Table of Content
The Hierarchy of HashSet is as follows:

Internal Working of a HashSet
All the classes of the Set interface are internally backed up by Map. HashSet uses HashMap for storing its object internally. You must be wondering that to enter a value in HashMap we need a key-value pair, but in HashSet, we are passing only one value.
Storage in HashMap: Actually the value we insert in HashSet acts as a key to the map Object and for its value, java uses a constant variable. So in the key-value pair, all the values will be the same.
To know more about the topic refer to Internal Working of HashSet.
Constructors of HashSet class
To create a HashSet, we need to create an object of the HashSet class. The HashSet class consists of various constructors that allow the possible creation of the HashSet. The following are the constructors available in this class.
Constructor | Description | Syntax |
|---|---|---|
HashSet() | This constructor is used to build an empty HashSet object in which the default initial capacity is 16 and the default load factor is 0.75. | HashSet<E> hs = new HashSet<E>(); |
HashSet(int initialCapacity) | This constructor is used to build an empty HashSet object in which the initialCapacity is specified at the time of object creation. | HashSet<E> hs = new HashSet<E>(int initialCapacity); |
HashSet(int initialCapacity, float loadFactor) | This constructor is used to build an empty HashSet object in which the initialCapacity and loadFactor are specified at the time of object creation. | HashSet<E> hs = new HashSet<E>(int initialCapacity, float loadFactor); |
HashSet(Collection) | This constructor is used to build a HashSet object containing all the elements from the given collection. In short, this constructor is used when any conversion is needed from any Collection object to the HashSet object. | HashSet<E> hs = new HashSet<E>(Collection C); |
Methods in Java HashSet
Method | Description |
|---|---|
| add(E e) | Used to add the specified element if it is not present, if it is present then return false. |
| clear() | Used to remove all the elements from the set. |
| contains(Object o) | Used to return true if an element is present in a set. |
| remove(Object o) | Used to remove the element if it is present in set. |
| iterator() | Used to return an iterator over the element in the set. |
| isEmpty() | Used to check whether the set is empty or not. Returns true for empty and false for a non-empty condition for set. |
| size() | Used to return the size of the set. |
| clone() | Used to create a shallow copy of the set. |
Performing Various Operations on HashSet
Let’s see how to perform a few frequently used operations on the HashSet.
1. Adding Elements in HashSet
To add an element to the HashSet, we can use the add() method. However, the insertion order is not retained in the HashSet. We need to keep a note that duplicate elements are not allowed and all duplicate elements are ignored.
Example:
// Java program to Adding Elements to HashSet
import java.util.*;
class GFG {
public static void main(String[] args){
// Creating an empty HashSet of string entities
HashSet<String> hs = new HashSet<String>();
// Adding elements using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
// Printing all string entries inside the Set
System.out.println("HashSet : " + hs);
}
}
Output
HashSet : [Geek, For, Geeks]
2. Removing Elements in HashSet
The values can be removed from the HashSet using the remove() method.
Example:
// Java program Illustrating Removal
// Of Elements from HashSet
import java.util.*;
class GFG {
public static void main(String[] args){
HashSet<String> hs = new HashSet<String>();
// Adding elements to above Set
// using add() method
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");
// Printing the elements of HashSet elements
System.out.println("HashSet : " + hs);
// Removing the element B
hs.remove("B");
// Printing the updated HashSet elements
System.out.println("HashSet after removing element : " + hs);
// Returns false if the element is not present
System.out.println("B exists in Set : " + hs.remove("B"));
}
}
Output
HashSet : [A, B, Geek, For, Geeks, Z] HashSet after removing element [A, Geek, For, Geeks, Z] B exists in Set : false
3. Iterating through the HashSet
Iterate through the elements of HashSet using the iterator() method. Also, the most famous one is to use the enhanced for loop.
Example:
// Java Program to Iterate Elements
// Of HashSet
import java.util.HashSet;
import java.util.Iterator;
public class HashSetIterationExample {
public static void main(String[] args) {
// Create a HashSet of Strings
HashSet<String> hs = new HashSet<>();
// Add elements to the HashSet
hs.add("A");
hs.add("B");
hs.add("Geeks");
hs.add("For");
hs.add("Geeks");
hs.add("Z");
// Using iterator() method to iterate
// Over the HashSet
System.out.print("Using iterator : ");
Iterator<String> iterator = hs.iterator();
// Traversing HashSet
while (iterator.hasNext())
System.out.print(iterator.next() + ", ");
System.out.println();
// Using enhanced for loop to iterate
// Over the HashSet
System.out.print("Using enhanced for loop : ");
for (String element : hs)
System.out.print(element + " , ");
}
}
Output
Using iterator : A, B, Geeks, For, Z, Using enhanced for loop : A , B , Geeks , For , Z ,
Performance of HashSet
HashSet extends Abstract Set<E> class and implements Set<E>, Cloneable, and Serializable interfaces where E is the type of elements maintained by this set. The directly known subclass of HashSet is LinkedHashSet.
Now for the maintenance of constant time performance, iterating over HashSet requires time proportional to the sum of the HashSet instance’s size (the number of elements) plus the “capacity” of the backing HashMap instance (the number of buckets). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
- Initial Capacity: The initial capacity means the number of buckets when the hashtable (HashSet internally uses hashtable data structure) is created. The number of buckets will be automatically increased if the current size gets full.
- Load Factor: The load factor is a measure of how full the HashSet is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.
Number of stored elements in the table
Load Factor = -----------------------------------------
Size of the hash table
Example: If internal capacity is 16 and the load factor is 0.75 then the number of buckets will automatically get increased when the table has 12 elements in it.
Effect on Performance:
Load factor and initial capacity are two main factors that affect the performance of HashSet operations. A load factor of 0.75 provides very effective performance with respect to time and space complexity. If we increase the load factor value more than that then memory overhead will be reduced (because it will decrease internal rebuilding operation) but, it will affect the add and search operation in the hashtable. To reduce the rehashing operation we should choose initial capacity wisely. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operation will ever occur.
Note: The implementation in a HashSet is not synchronized, in the sense that if multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set as shown below:
Set s = Collections.synchronizedSet(new HashSet(…));
Inherited Methods in Java HashSet
Classes and Interfaces | Method | Description |
|---|---|---|
java.util.AbstractSet | equals() | Used to verify the equality of an Object with a HashSet and compare them. The list returns true only if both HashSet contains the same elements, irrespective of order. |
| hashcode() | Returns the hash code value for this set. | |
| removeAll(collection) | This method is used to remove all the elements from the collection which are present in the set. This method returns true if this set changes as a result of the call. | |
java.util.AbstractCollection | addAll(collection) | This method is used to append all of the elements from the mentioned collection to the existing set. |
| containsAll(collection) | This method is used to check whether the set contains all the elements present in the given collection or not. | |
| retainAll(collection) | This method is used to retain all the elements from the set which are mentioned in the given collection. This method returns true if this set changed as a result of the call. | |
| toArray() | This method is used to form an array of the same elements as that of the Set. | |
| toString() | The toString() method of Java HashSet is used to return a string representation of the elements of the HashSet Collection. | |
java.util.Collection | parallelStream() | Returns a possibly parallel Stream with this collection as its source. |
| removeIf?(Predicate<? super E> filter) | Removes all of the elements of this collection that satisfy the given predicate. | |
| stream() | Returns a sequential Stream with this collection as its source. | |
| toArray?(IntFunction<T[]> generator) | Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array. | |
java.lang.Iterable | forEach?(Consumer<? super T> action) | Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. |
java.util.Set | addAll?(Collection<? extends E> c) | Adds all of the elements in the specified collection to this set if they’re not already present (optional operation). |
| containsAll?(Collection<?> c) | Returns true if this set contains all of the elements of the specified collection. | |
| equals?(Object o) | Compares the specified object with this set for equality. | |
| hashCode() | Returns the hash code value for this set. | |
| removeAll?(Collection<?> c) | Removes from this set all of its elements that are contained in the specified collection (optional operation). | |
| retainAll?(Collection<?> c) | Retains only the elements in this set that are contained in the specified collection (optional operation). | |
| toArray() | Returns an array containing all of the elements in this set. | |
| toArray?(T[] a) | Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array. |
FAQs – Java HashSet
What is HashSet in Java?
HashSet is a type of class, which extends AbstractSet and implements Set interfaces.
Why is HashSet used?
HashSet is used for avoiding duplicate data and to find value with the fast method.
Differences between HashSet and HashMap.
Basis | HashSet | HashMap |
|---|---|---|
| Implementation | HashSet implements a Set interface. | HashMap implements a storesMap interface. |
| Duplicates | HashSet doesn’t allow duplicate values. | HashMap stores the key and value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value. |
| Number of objects during storing objects | HashSet requires only one object add(Object o). | HashMap requires two objects put(K key, V Value) to add an element to the HashMap object. |
| Dummy value | HashSet internally uses HashMap to add elements. In HashSet, the argument passed in add(Object) method serves as key K. Java internally associates a dummy value for each value passed in add(Object) method. | HashMap does not have any concept of dummy value. |
| Storing or Adding a mechanism | HashSet internally uses the HashMap object to store or add the objects. | HashMap internally uses hashing to store or add objects |
| Faster | HashSet is slower than HashMap. | HashMap is faster than HashSet. |
| Insertion | HashSet uses the add() method for adding or storing data. | HashMap uses the put() method for storing data. |
| Example | HashSet is a set, e.g. {1, 2, 3, 4, 5, 6, 7}. | HashMap is a key -> value pair(key to value) map, e.g. {a -> 1, b -> 2, c -> 2, d -> 1}. |
Differences between HashSet and TreeSet in Java.
Basis | HashSet | TreeSet |
|---|---|---|
| Speed and internal implement the, throw action | For operations like search, insert, and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. | TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data. Also, it supports operations like higher() (Returns least higher element), floor(), ceiling(), etc. These operations are also O(Log n) in TreeSet and not supported in HashSet. TreeSet is implemented using a Self Balancing Binary Search Tree (Red-Black Tree). TreeSet is backed by TreeMap in Java. |
| Ordering | Elements in HashSet are not ordered. | TreeSet maintains objects in Sorted order defined by either the Comparable or Comparator method in Java. TreeSet elements are sorted in ascending order by default. It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc. |
| Null Object | HashSet allows the null object. | TreeSet doesn’t allow null Object and throws NullPointerException, Why, is because TreeSet uses compareTo() method to compare keys, and compareTo() will throw java.lang.NullPointerException. |
| Comparison | HashSet uses the equals() method to compare two objects in the Set and for detecting duplicates. | TreeSet uses compareTo() method for the same purpose. If equals() and compareTo() are not consistent, i.e. for two equal objects equals should return true while compareTo() should return zero, then it will break the contract of the Set interface and will allow duplicates in Set implementations like TreeSet. |


