Java HashSet

In this tutorial, we will learn about what is java.util.HashSet, its features and use cases of it along with working examples of it using custom class objects.

What is a Set?

Set is a collection of elements which belongs to the same group but all are unique and does not allow the same elements. Suppose a pack of cards, each card is a unique and does not have any duplicates.

HashSet class

In Java, java.util.HashSet is a class from collections framework which is an implementation of the Set interface and does not allow duplicate elements and follows an unordered collection of unique elements, meaning that it does not allow duplicate elements to add and no guarantee of insertion order.

Behaviour of HashSet:

The elements in a HashSet are not ordered, meaning that they do not follow a specific sequence or position. This is because HashSet uses a hash table to store its elements, which does not maintain order.

HashSet does not allow duplicate elements. If you try to add an element that already exists in the HashSet, it will not be added. For Custom class objects need to override the equals and hashCode to find duplicates.

As HashSet uses a hash table to store its elements, it has fast retrieval times for elements. This means that you can quickly check if an element is in the HashSet, and retrieve it if it exists.

HashSet allows iteration over its elements using the iterator() method. This allows you to loop over the elements in the HashSet and perform operations on them.

Where HashSet can be used:

  1. Mainly used to eliminate duplicates.
  2. Prevent duplicate orders in case of online transactions.
  3. Can be used as part in graph algorithm.

HashSet example with in-built equals() and hashCode() methods:

Consider an example of HashSet, where we create an HashSet of strings and perform some basic operations on it. String class contains implementation of the equals() and hashCode() to identify duplicate elements hence no need to implement these methods.

CopiedCopy Code
import java.util.HashSet;
public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("banana"); // This will not be added to the set
        System.out.println("HashSet contains: " + set);
        System.out.println("Size of HashSet: " + set.size());
        // Check if an element exists in the HashSet
        if (set.contains("apple")) {
            System.out.println("HashSet contains the element 'apple'");
        }
        // Iterate over the elements in the HashSet
        for (String element : set) {
            System.out.println("Element in HashSet: " + element);
        }
        // Remove an element from the HashSet
        set.remove("orange");
        System.out.println("HashSet after removing 'orange': " + set);
        // Clear all elements from the HashSet
        set.clear();
        System.out.println("HashSet after clearing all elements: " + set);
    }
}

Output:

HashSet contains: [banana, orange, apple]
Size of HashSet: 3
HashSet contains the element 'apple'
Element in HashSet: banana
Element in HashSet: orange
Element in HashSet: apple
HashSet after removing 'orange': [banana, apple]
HashSet after clearing all elements: []

Explanation:

We have created an HashSet class object, added four elements into the set and printed what contains in it and size of the set. Checking whether apple element is present in the set later we iterated over the set elements. Removed orange element and cleared the set.

HashSet example with custom equals() and hashCode() methods:

In this example, we will add custom class objects to the HashSet by overriding hashCode() and equals() methods in custom class for identifying duplicates while adding to the HashSet.

CopiedCopy Code
import java.util.HashSet;
import java.util.Set;
public class SetCustomClass {
	public static void main(String[] args) {
		Set<ATM> atms = new HashSet<ATM>();
		ATM atm1 = new ATM("ICICI","India");
		ATM atm2 = new ATM("Danske","US");
		ATM atm3 = new ATM("HDFC","UK");
		ATM atm4 = new ATM("ICICI","India");
		System.out.println("Element added :"+atms.add(atm1));
		System.out.println("Element added :"+atms.add(atm2));
		System.out.println("Element added :"+atms.add(atm3));
		System.out.println("Element added :"+atms.add(atm4));
		System.out.println("Element added :"+atms);	
	}
	static class ATM {
		public String atmName;
		public String location;
		public ATM(String atmName, String location) {
			this.atmName = atmName;
			this.location = location;
		}
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((atmName == null) ? 0 : atmName.hashCode());
			result = prime * result + ((location == null) ? 0 : location.hashCode());
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			ATM other = (ATM) obj;
			if (atmName.equals(other.atmName) && location.equals(other.location))
				return true;
			return false;
		}
		@Override
		public String toString() {
			return "ATM [atmName=" + atmName + ", location=" + location + "]";
		}
	}
}

Output:

Element added :true
Element added :true
Element added :true
Element added :false
Element added :[ATM [atmName=HDFC, location=UK], ATM [atmName=Danske, location=US], ATM [atmName=ICICI, location=India]]

Explanation:

In the above example, we have created Set class object to add custom class(ATM) objects. And we have overridden the equals and hashCode methods in ATM class.

Tried adding the elements inside it, when we added unique elements, it returned true. When added duplicate element it returned false, to find duplicate elements Set used overridden methods under ATM class. Finally, we printed elements present in the set to console.

Conclusion:

In this tutorial, we have covered what HashSet , its features along with working examples including custom class elements also.