Java HashSet Class



Introduction

The Java HashSet class implements the Set interface, backed by a hash table. A HashSet is a collection of elements where every element is unique element. The HashSet class is part of the Collections Framework in Java.

The HashSet removes duplicate elements from the hash table automatically. The HashSet is not thread-safe, and to make it thread-safe, synchronization is needed externally. It also implements the Serializable and the Cloneable interfaces.

Characterstics

The following are the important points about HashSet −

  • This class makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
  • This class permits the null element.
  • Adding, removing, or checking if an element is present takes constant time of O(1), which is fast compared to other interfaces.

Class declaration

Following is the declaration for java.util.HashSet class −

public class HashSet<E>
   extends AbstractSet<E>
   implements Set<E>, Cloneable, Serializable

Parameters

E − This is the type of elements maintained by this set.

What are initialCapacity and loadFactor?

In the HashSet class, the capacity refers to the number of buckets in the hash table. The default capacity of a HashSet is 16. When the number of elements exceeds the given capacity, the HashSet automatically resizes(increases) to maintain performance.

Suppose the load factor of a hash set is 0.7. So, whenever our hash set is filled by 70%, the elements of the current HashSet are moved to a new hash table, which is double the size of the original hash table, and the default value of the load factor is 0.75.

Initializing a HashSet Class

For the initialization of the HashSet class, we need to create an object of it. The HashSet class provides three methods to initialize a HashSet. They are as follows −

HashSet()

This constructor allows us to create an empty hash set. Below, we are creating a HashSet with the name "hashset1"

HashSet<Type> hashset1 = new HashSet<>();

HashSet(initialCapacity, loadFactor)

This constructor allows us to create an empty hash set with the specified initial capacity and load factor. Below, we are creating a HashSet with the name "hashset2"

HashSet<Type> hashset2 = new HashSet<>(int initialCapacity, float loadFactor);

HashSet(Collection C)

This constructor allows us to create an ordered set that contains all the elements of a specified collection. Below, we are creating a HashSet with the name "hashset3"

HashSet<Type> hashset3 = new HashSet<>(Collection);

Here, C is the collection whose elements are to be placed in a hash set. It can also throw a NullPointerException if the specified collection is null.

Example

Below is an example of initializing a HashSet in Java −

package com.tutorialspoint;

import java.util.HashSet;
import java.util.ArrayList;

public class HashSetDemo {
   public static void main(String args[]) {
      
      // HashSet with default constructor
      HashSet<Integer> hashset1 = new HashSet<>();
      hashset1.add(1);
      hashset1.add(2);
      hashset1.add(3);
      System.out.println("HashSet1: " + hashset1);

      // HashSet with initial capacity and loadfactor
      HashSet<Integer> hashset2 = new HashSet<>(20, 0.75f);
      hashset2.add(4);
      hashset2.add(5);
      hashset2.add(6);
      System.out.println("HashSet2 with capacity and loadfactor: " + hashset2);

      // Using collection with HashSet
      ArrayList<Integer> list = new ArrayList<>();
      list.add(7);
      list.add(8);
      list.add(9);
      HashSet<Integer> hashset3 = new HashSet<>(list);
      System.out.println("HashSet3 with collections: " + hashset3);
   }
}

Output

Let us compile and run the above program. This will produce the following result −

HashSet1: [1, 2, 3]
HashSet2 with capacity and loadfactor: [4, 5, 6]
HashSet3 with collections: [7, 8, 9]

Class Constructors

The following are the class constructors supported by the HashSet in Java −

Sr.No. Constructor & Description
1

HashSet()

This constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).

2

HashSet(Collection<? extends E> c)

This constructs a new set containing the elements in the specified collection.

3

HashSet(int initialCapacity)

This constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).

4

HashSet(int initialCapacity, float loadFactor)

This constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.

Class Methods

The following are the class methods supported by the HashSet in Java −

Sr.No. Method & Description
1 boolean add(E e)

This method adds the specified element to this set if it is not already present.

2 void clear()

This method removes all of the elements from this set.

3 Object clone()

This method returns a shallow copy of this HashSet instance, the elements themselves are not cloned.

4 boolean contains(Object o)

This method returns true if this set contains the specified element.

5 boolean isEmpty()

This method returns true if this set contains no elements.

6 Iterator<E> iterator()

This method returns an iterator over the elements in this set.

7 boolean remove(Object o)

This method removes the specified element from this set if it is present.

8 int size()

This method returns the number of elements in this set(its cardinality).

9 Spliterator<E> spliterator()

This method returns a late-binding and fail-fast Spliterator over the elements in this set.

Methods inherited

This class inherits methods from the following classes −

  • java.util.AbstractSet
  • java.util.AbstractCollection
  • java.util.Object
  • java.util.Set

Adding Elements to a HashSet

The HashSet add() method is used to add entries to the HashSet, and the addAll() method is used to add the existing values of the HashSet to a new HashSet. We've created a HashSet object of Integer. Then few entries are added using the add() method, and then the set is printed. Then, using the addAll() method, the current elements were added to a new HashSet, and the set was printed.

Example

Below is an example of adding elements to a HashSet using the add() and addAll() methods in Java −

package com.tutorialspoint;

import java.util.HashSet;

public class HashSetDemo {
   public static void main(String args[]) {
      
      // create hash set
      HashSet <Integer> set = new HashSet <>();

      // populate hash set using the add() method
      set.add(1); 
      set.add(2);
      set.add(3);  

      // checking elements in hash set
      System.out.println("Hash set values: "+ set);
      
      HashSet <Integer> newset = new HashSet <>();
      
      // Using the addAll method
      newset.addAll(set);
      newset.add(4);
      System.out.println("The new HashSet is: " + newset);
   }    
}

Output

Let us compile and run the above program. This will produce the following result −

Hash set values: [1, 2, 3]
The new HashSet is: [1, 2, 3, 4]

Accessing Elements from a HashSet

The HashSet provides the iterator() method for accessing the elements from a HashSet. We've created a HashSet object of Integer. Then few entries are added using the add() method, and then the iterator() method is used to print the set elements.

Example

Below is an example of accessing elements from a HashSet using the iterator() method in Java −

package com.tutorialspoint;

import java.util.HashSet;
import java.util.Iterator;

public class HashSetDemo {
   public static void main(String args[]) {
      
      // create hash set
      HashSet <Integer> set = new HashSet <>();

      // populate hash set using the add() method
      set.add(10); 
      set.add(20);
      set.add(30);  
      
      // using the iterator for accessing the elements
      Iterator<Integer> iterate = set.iterator();
      while(iterate.hasNext()) {
            System.out.println(iterate.next());
       }    
   }    
}

Output

Let us compile and run the above program. This will produce the following result −

10
20
30

Removing Elements from a HashSet

The HashSet remove() method is used to remove entries from the HashSet, and the removeAll() method is used to remove all the existing values from the HashSet. We've created a HashSet object of Integer. Then few entries are removed using the remove() method, and then the set is printed. Then, using the removeAll() method, the set is cleared and checked if empty.

Example

Below is an example of removing elements from a HashSet using the remove() and removeAll() methods in Java −

package com.tutorialspoint;

import java.util.HashSet;

public class HashSetDemo {
   public static void main(String args[]) {
      
      // create hash set
      HashSet <Integer> set = new HashSet <>();

      // populate hash set using the add() method
      set.add(10); 
      set.add(20);
      set.add(30);  
      
      System.out.println("HashSet: " + set);  
      
      //  using the remove() method
      set.remove(20);
      System.out.println("HashSet after deletion: " + set);
      
      // using the removeAll() method
      set.removeAll(set);
      System.out.println("HashSet is empty: " + set.isEmpty());
   }    
}

Output

Let us compile and run the above program. This will produce the following result −

HashSet: [20, 10, 30]
HashSet after deletion: [10, 30]
HashSet is empty: true
Advertisements