Updates
  • Starting New Weekday Batch for Full Stack Java Development on 15 September 2025 @ 02:00 PM to 04:00 PM
  • Starting New Weekday Batch for MERN Stack Development on 29 September 2025 @ 04:00 PM to 06:00 PM
Join Course

Java Full Stack Developer Training Center in Noida

HashSet

HashSet is a class available in the java.util package, and it is a set type collection because it implements the java.util.Set interface

HashSet Important Points:

1. Using a HashSet, or an object of the java.util.HashSet class, we can store different types of elements without duplicity.
2. We can traverse a HashSet in forward order only using an Iterator.
3. We cannot traverse a HashSet using List-Iterator and Enumeration.
4. HashSet also uses Index representation to store its elements, similar to ArrayList or Vector, allowing random access to elements using their index position.
5. The java.util.HashSet class methods are not synchronized in nature.
6. HashSet doesn’t store data in the added order; it stores elements in an unsorted way because a HashSet internally uses HashMap.
7. Because the java.util.HashSet class implements the java.lang.Cloneable and java.io.Serializable interfaces, a HashSet is eligible for cloning and serialization.
8. All Set type Collections internally work on a Map.

Constructor of java.util.HashSet class:

1. public java.util.HashSet(): It is the default constructor of the java.util.HashSet class. Using this constructor, we can create a simple and empty HashSet in a Java program as needed. When this constructor is used, the initial capacity will be 16, and the load factor will be 0.75 by default.

2. public java.util.HashSet(java.util.Collection<? extends E>): It is a parameterized constructor with a java.util.Collection type parameter. This constructor is used to create a HashSet containing all the elements of the specified Collection.

            
import java.util.ArrayList;
import java.util.HashSet;
public class JTC {
   public static void main(String[] args) {
      // Creating HashSet by default constructor.
      HashSet set1 = new HashSet();
      System.out.println("size of set1 :- " + set1.size());
      System.out.println("set1 :- " + set1);
      ArrayList list1 = new ArrayList();
      list1.add(101);
      list1.add(true);
      list1.add(12.34);
      list1.add("Hello");
      list1.add('A');
      // Creating HashSet using HashSet(Collection) constructor.
      HashSet set2 = new HashSet < > (list1);
      System.out.println("set2 :- " + set2.size());
      System.out.println("set2 :- " + set2);
   }
}
    size of set1 :- 0
    set1 :- []
    set2 :- 5
    set2 :- [A, 12.34, Hello, 101, true]
            

In this example, we first create an object of the java.util.HashSet class by invoking its default constructor, resulting in an empty HashSet. In the subsequent section of the program, we create another object of the java.util.HashSet class using the java.util.HashSet(Collection) constructor. Here, we have an ArrayList, and we pass this ArrayList as an argument to the constructor. Finally, we create a HashSet that contains all the elements of the ArrayList. It's important to note that the element sequence in the HashSet may not be the same as the ArrayList, as it stores elements based on its internal implementation.

3. public java.util.HashSet(int): We use the java.util.HashSet(int) constructor to create an empty HashSet with a specified initial capacity. The default load factor for this constructor is 0.75.

4. public java.util.HashSet(int, float): This constructor enables the creation of a HashSet with a custom capacity and load factor.

Initial Capacity: In HashSet, which operates on HashMap internally, the elements are stored in a key-value pair using a hashing mechanism within buckets. The Initial Capacity parameter determines the number of buckets when creating a HashSet

Load Factor: The Load Factor in HashSet determines how the HashSet refreshes when the number of elements exceeds the product of the Load Factor and the Capacity. When the number of elements exceeds this threshold, the HashSet is automatically refreshed, increasing its capacity.

Important Method of java.util.HashSet class:

1. public java.util.Iterator iterator(): This method is basically used to return a java.util.Iterator type object associated with the current HashSet. Using the Iterator type object, we can iterate through the HashSet using the hasNext() and next() methods.

            
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class JTC {
   public static void main(String[] args) {
      HashSet set = new HashSet();
      set.add(101);
      set.add("Hello");
      set.add('A');
      set.add(true);
      set.add(new JTC());
      set.add(null);
      set.add(12.34);
      Iterator iterator = set.iterator();
      while (iterator.hasNext()) {
         System.out.println(iterator.next());
      }
   }
}
    null
    A
    12.34
    Hello
    101
    com.P1.JTC@3d012ddd
    true
            

2. public int size(): We use this method to get the number of elements in the current HashSet.

3. public boolean isEmpty(): It returns true if the current HashSet does not contain any elements, otherwise it returns false.

4. public boolean add(E): It adds the specified element to the current HashSet. If the element is not already present in the HashSet, it returns true and adds the element; otherwise, it returns false.

5. public boolean remove(java.lang.Object): It removes the specified element from the current HashSet if the element is present, returning true; otherwise, it returns false.

            
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class JTC {
   public static void main(String[] args) {
      HashSet set = new HashSet();
      System.out.println("Added :- " + set.add(101));
      System.out.println("Added :- " + set.add("Hello"));
      System.out.println("Added :- " + set.add('A'));
      System.out.println("Added :- " + set.add(true));
      System.out.println("Added :- " + set.add(101));
      System.out.println("Added :- " + set.add(new JTC()));
      System.out.println("Added :- " + set.add(null));
      System.out.println("Added :- " + set.add(12.34));
      System.out.println("Number of elements :- " + set.size());
      System.out.println("Empty Status :- " + set.isEmpty());
      System.out.println("Elements availability :- " + set.contains("Hello"));
      System.out.println("Elements availability :- " + set.contains("JTC"));
      System.out.println("set :- " + set);
      System.out.println("Removing Element :- " + set.remove(101));
      System.out.println("set :- " + set);
      System.out.println("Removing Element :- " + set.remove("JTC"));
   }
}
    Added :- true
    Added :- true
    Added :- true
    Added :- true
    Added :- false
    Added :- true
    Added :- true
    Added :- true
    Number of elements :- 7
    Empty Status :- false
    Elements availability :- true
    Elements availability :- false
    set :- [null, A, 12.34, Hello, 101, com.P1.JTC@515f550a, true]
    Removing Element :- true
    set :- [null, A, 12.34, Hello, com.P1.JTC@515f550a, true]
    Removing Element :- false
            

In the above example, we are using different methods of the java.util.HashSet class, such as add(), remove(), contains(), isEmpty(), and size() methods.
In the first section of the program, we are creating an empty HashSet using the default constructor of the java.util.HashSet class and adding different elements using the add() method. In this section, we can notice one point: when we are trying to add a duplicate element (101) into the HashSet, it is returning false and not adding the duplicate element.
After that, we are invoking the size() method, which returns the number of elements in the current HashSet, and in this case, it is returning 7.
In the next line, we are calling the isEmpty() method on the same HashSet, and it is returning false because the current HashSet is not empty.
After that, we are calling the contains() method two times along with the current HashSet to check whether the elements 'Hello' and 'JTC' are available in the HashSet or not. We can see that the contains() method is returning true and false, respectively, because 'Hello' is in the HashSet, and 'JTC' is not an element of the HashSet.
And finally, we are invoking the remove() method. In the first call, we can see that it returns true and removes '101' from the HashSet. However, in the second invocation, it returns false because we have passed 'JTC' as an argument, and 'JTC' is not a member of the current HashSet.