Java HashSet | Example Program

The collections framework provides two general-purpose set implementations in Java: HashSet and TreeSet. In this tutorial, we will learn HashSet in Java with example programs in an easy way.

HashSet class was introduced in Java 1.2 version and it is present in java.util.HashSet package. It internally uses HashMap to store unique elements. It is much faster and gives constant-time performance for insertion, removal, and retrieval operations.

HashSet in Java


➲ Java HashSet is an unordered collection of objects which contains only unique elements. It internally uses HashMap to store its element by using a mechanism called hashing

➲ HashSet does not allow duplicate elements. If you try to add a duplicate element in HashSet, the older element would be overwritten. 

➲ It allows only one null element. If you add more than one null element, it would still return only one null value.

➲ HashSet does not maintain any order in which elements are added. The order of the elements will be unpredictable. It will return in any random order.

➲ HashSet is much faster due to the use of hashing technique and gives constant-time performance for adding (insertion), retrieval, removal, contains, and size operations. Hashing provides constant execution time for methods like add(), remove(), contains(), and size() even for the large set.


➲ HashSet class is not synchronized that means it is not thread-safe. Therefore, multiple threads can use the same HashSet’s object at the same time and will not give deterministic final output.  If you want to synchronize HashSet, use Collections.synchronizeSet() method.

➲ The iterator returned by HashSet class is fail-fast which means any modification happened in the HashSet during iteration, will throw ConcurrentModificationException.

Java HashSet Hierarchy


HashSet class extends AbstractSet class and implements the Set interface. The AbstractSet class itself extends AbstractCollection class. It also implements cloneable and serializable marker interfaces. The hierarchy diagram of HashSet class can be shown in below figure.

Java HashSet hierarchy diagram

HashSet Class Declaration


Let’s see the declaration for java.util.HashSet class.

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

Constructors of Java HashSet class


The following constructors are defined for Java HashSet class. They are as follows:
1. HashSet(): It constructs an empty HashSet (i.e, default HashSet). The default capacity is 16.

2. HashSet(int initialCapacity): It initializes the capacity of HashSet. When the set capacity reaches full and a new element is added, the capacity of the hash set is expended automatically. The internal structure will double in size before adding a new element.

3. HashSet(int initialCapacity, float fillRatio): It initializes capacity and fill ratio (also called load factor or load capacity) of the hash set. When the number of elements is greater than capacity of HashSet, the size of the HashSet is grown automatically by multiplying capacity with load factor. The default value of the load factor is 0.75. The value of the fill ratio ranges from 0.0 to1.0.

4. HashSet(Collection c): It initializes HashSet by using elements of c. This constructor acts as a copy constructor. It copies elements from one collection into the newly created collection. We cannot provide a custom initial capacity or fill ratio.

If the original collection had duplicate elements, only one duplicate element will be allowed in the final created set. 

Note: Constructors that do not take a load factor, 0.75 is used. 

Methods of Java HashSet class


The HashSet class does not define any additional methods. It inherits methods of its parent classes and methods of the implemented interface. The various methods provided by its super classes and interfaces are as follows:

1. Adding a single element: If you want to add a single element, call add() method. The general syntax is as follows:

public boolean add(Object o)

The add() method takes a single argument of element to add. This method returns true if set does not already contain a specified element.

2. Adding another collection of elements: If you want to add a group of elements from another collection to the set, call addAll() method. The general syntax of addAll method is as follows:

public boolean addAll(Collection c)

Each element in the collection will be added to the current set via calling add() method on each element. It returns true if the current set changes. If no elements are added, false is returned. A UnsupportedOperationException will be thrown when a current set does not support adding elements.



3. Removing single element: If you wish to remove a single element at a time, use remove() method.
public boolean remove(Object o)

To remove an element, set internally use equals() method for each element. If the element is found, element is removed from set and returns true. If not found, false is returned. If the removal is not supported, you will get UnsupportedOperationException

4. Removing all elements: To remove all elements from a set, use clear() method. The general syntax is:

public void clear() // It returns nothing.

5. Checking for Existing element: To check a specific element is present or not in the set, use contains() method.     

public boolean contains(Object element)

If the specified element is found in the set, it returns true otherwise false. The equality checking is done through the element’s equal method.

6. Checking size: If you wish to know how many elements are in a set, call size() method.

public int size()

7. Checking for Empty: If you wish to check whether HashSet contains elements or not. Call isEmpty() method. The syntax is as follows:

public boolean isEmpty()

8. Copying and Cloning set: Since HashSet implements cloneable interface. So, we can create a shallow copy of that hash set by calling clone() method of HashSet.

public Object clone()
9. Checking for Equality: The HashSet class defines equality by using equals() method on each element within set.
public boolean equals(Object o)
10. Hashing Collections: The HashSet class overrides the hashCode() method to define an appropriate hash code value for the set. It returns the same hash code by sum up all hash codes of all the elements. 
public int hashCode()

Java HashSet Example Program


How to Add an Element to Java HashSet?

1. In this example program, we will see how to:
➧ Create HashSet object.
➧ Adding elements to HashSet.
➧ Adding duplicate elements will be ignored.
➧ Adding null element.

Program source code 1: 

package hashSetTest; 
import java.util.HashSet; 
public class HashSetExample1 
{ 
public static void main(String[] args) 
{ 
// Create a HashSet object. 
   HashSet<String> set = new HashSet<String>(); 
// Adding elements to HashSet. 
   set.add("First"); 
   set.add("Second"); 
   set.add("Third"); 
   set.add("Fourth"); 
   set.add("Fifth"); 
// Adding duplicate elements that will be ignored. 
   set.add("First"); 
   set.add("Third"); 

// Adding of null elements. 
   set.add(null); 
   set.add(null); // Ignored. 
 System.out.println("Unordered and No Duplicate HashSet Elements"); 
 System.out.println(set); 
 } 
}
Output: 
       Unordered and No Duplicate HashSet Elements 
       [null, Second, Third, First, Fourth, Fifth]

How to Add Elements from Existing Collection to HashSet in Java?


Let’s take an example program, we will learn how to add all elements from existing collection to HashSet.

Program source code 2:

package hashSetTest; 
import java.util.ArrayList; 
import java.util.HashSet; 
public class HashSetExample2 
{ 
public static void main(String[] args) 
{ 
// Create an ArrayList object. 
   ArrayList<String> al = new ArrayList<String>(); 
    al.add("Monday"); 
    al.add("Tuesday"); 
    al.add("Wednesday"); 
    al.add("Thursday"); 
    al.add("Friday"); 
// Adding duplicate elements. 
    al.add("Monday"); 
    al.add("Friday"); 
   System.out.println("Original Elements Order "); 
   System.out.println(al); 

// Create HashSet object. 
   HashSet<String> hset = new HashSet<String>(); 
// Call addAll() method for adding all elements from existing collection to HashSet. 
   hset.addAll(al); 
  System.out.println("Unordered HashSet Elements without Duplicate elements"); 
  System.out.println(hset); 
  } 
}
Output: 
       Original Elements Order 
       [Monday, Tuesday, Wednesday, Thursday, Friday, Monday, Friday] 
       Unordered HashSet Elements without Duplicate elements 
       [Monday, Thursday, Friday, Wednesday, Tuesday]

How to Remove Elements from HashSet?


This example program will show you how to:
➧ Remove a specific element from a HashSet.
➧ Remove all elements available in a Set.

Program source code 3:

package hashSetTest; 
import java.util.HashSet; 
public class HashSetExample3 
{ 
public static void main(String[] args)
{ 
 HashSet<Integer> hset = new HashSet<Integer>(); 
 hset.add(5); 
 hset.add(10); 
 hset.add(15); 
 hset.add(20); 
System.out.println("Initial list of elements"); 
System.out.println(hset); 

// Removing a specific element from HashSet. 
   hset.remove(10); 
   System.out.println("List of elements after removing 10"); 
   System.out.println(hset); 
 
 HashSet<Integer> hset2 = new HashSet<Integer>(); 
  hset2.add(10); 
  hset2.add(25); 
  hset.addAll(hset2); 
 System.out.println("List of Elements after adding elements from existing collection"); 
 System.out.println(hset); 

// Removing all new elements from HashSet.
   hset.removeAll(hset2); 
   System.out.println("List of Elements after removing elements from hset2"); 
   System.out.println(hset); 

// Removing all elements available in HashSet.
   clear(); 
   System.out.println("After invoking clear() method: "+hset); 
  } 
}
Output: 
      Initial list of elements 
      [20, 5, 10, 15] 
      List of elements after removing 10 
      [20, 5, 15] 
      List of Elements after adding elements from existing collection 
      [20, 5, 25, 10, 15] 
      List of Elements after removing elements from hset2 
      [20, 5, 15] 
      After invoking clear() method: [ ]

How to check Number of Elements in Java HashSet?


In this example program, we will see how to:
➧ Find the number of elements in a set.
➧ Check HashSet is empty or not.

Program source code 4: 

package hashSetTest; 
import java.util.HashSet; 
import java.util.Set; 
public class HashSetExample4 
{ 
public static void main(String[] args) 
{ 
   Set<String> pCountry = new HashSet<String>(); 
// Check that HashSet is empty or not.
   System.out.println("Is popularCountries set empty? : " + pCountry.isEmpty()); 
   System.out.println("Number of countries in HashSet before adding: " +pCountry.size()); 
   pCountry.add("INDIA"); 
   pCountry.add("USA"); 
   pCountry.add("UK"); 
   pCountry.add("FRANCE"); 

// Find size of HashSet. 
   System.out.println("Number of countries in HashSet after adding: " + pCountry.size()); 
  } 
}
Output: 
      Is popularCountries set empty? : true 
      Number of countries in HashSet before adding: 0 
      Number of countries in HashSet after adding: 4

How to check Existing Element in HashSet?


This example program will show you how to check an element exists in Java hash set or not. We will use contains() method for this.

Program source code 5:

package hashSetTest; 
import java.util.HashSet; 
import java.util.Set; 
public class HashSetExample4 
{ 
public static void main(String[] args) 
{ 
 Set<String> set = new HashSet<String>(); 
 System.out.println("Is set empty? : " + set.isEmpty()); 
 System.out.println("Number of elements in HashSet before adding: " +set.size()); 
  set.add("Dollar"); 
  set.add("Indian Rupee"); 
  set.add("Euro"); 
  set.add("Yen"); 
 System.out.println("List of Elements in set"); 
 System.out.println(set); 
 System.out.println("Number of elements in the HashSet after adding: " + set.size()); 

// Call contains() method to check an element exists in set or not. 
   if(set.contains("Dollar"))
   { 
     System.out.println("Does Element 'Dollar' exist in set?"); 
     System.out.println("Yes, Element 'Dollar' exists in set"); 
   } 
 else
 { 
   System.out.println("No, Element 'Dollar' does not exist in set"); 
  } 
 System.out.println("Does Element 'Dinar' exist in set?"); 
 if(set.contains("Dinar"))
 { 
   System.out.println("Yes, Element 'Dinar' exists in set "); 
  } 
 else { 
    System.out.println("No, Element 'Dinar' does not exist in set"); 
   } 
  } 
}
Output: 
       Is set empty? : true 
       Number of elements in HashSet before adding: 0 
       List of Elements in set 
       [Yen, Dollar, Indian Rupee, Euro] 
       Number of elements in HashSet after adding: 4 
       Does Element 'Dollar' exist in set? 
       Yes, Element 'Dollar' exists in set 
       Does Element 'Dinar' exist in the set? 
       No, Element 'Dinar' does not exist in the set

How to create User-defined Object of HashSet?


Let’s create a program where we will create a user-defined object of HashSet in Java.

Program source code 6:

package hashSetTest; 
public class Student 
{ 
// Declare instance variables. 
   String name, sName; 
   int id; 
public Student(String name, String sName, int id) 
{ 
  this.name = name; 
  this.sName = sName; 
  this.id = id; 
  } 
 } 
package hashSetTest; 
import java.util.HashSet; 
public class HashSetExample6 
{ 
 public static void main(String[] args) 
 { 
// Create a user-defined HashSet object of type Student. 
   HashSet<Student> hset = new HashSet<Student>(); 
// Create objects of Student class and pass the parameters. 
   Student s1 = new Student("John", "RSVM", 0012); 
   Student s2 = new Student("Shubh", "DPS", 1234); 
   Student s3 = new Student("Ricky", "DAV", 9876); 

// Adding elements to HashSet and pass reference variables s1, s2, s3. 
   hset.add(s1); 
   hset.add(s2); 
   hset.add(s3); 
// Traversing HashSet. 
   for(Student s:hset)
   { 
     System.out.println(s.name+" "+s.sName+" "+s.id); 
    } 
  } 
}
Output: 
       Ricky DAV 9876 
       John RSVM 10 
       Shubh DPS 1234

When to use HashSet in Java?


HashSet in Java is used when
1. We don’t want to store duplicate elements.
2. We want to remove duplicate elements from the list.
3. HashSet is more preferred when add and remove operations are more as compared to get operations.
4. We are not working in a multithreading environment.

Final words 
Hope that this tutorial has covered almost all the important topics in Java HashSet with example programs. I hope that you will have understood this topic and enjoyed programming.
Thanks for reading!!!

 

Leave a Comment