HashSet Class in Java With Program Example

Share

Set interface doesn’t provide any additional method, as a result, implementation classes use only collection interface methods.
HashSet is an implementing class of Set interface and it represents Hash Table as its underlying data structure. It is a collection of unordered unique elements that don’t allow duplicates. It also doesn’t preserve insertion order as it uses hash code to store an element. Meaning, the elements are stored based on some hash values and can be retrieved in any order.

It uses several methods of Collection interface i.e. add(), remove(), contains(). The add() method returns false and doesn’t add an element if one tries to insert a duplicate element. The advantage of using HashSet, it makes searching faster.

It can store different types of objects and allows at most a single null value to hashSet.
It also implements the Serializable and Collneable interface.

Set is the best choice when the frequent search operation is required.

Syntax:

Set<String> set = new HashSet<String>();

Point to Remember :

  1. It doesn’t preserve insertion order
  2. It allows atmost single null value
  3. It can store various type of objects at the same time
  4. It uses hash table as its underlying data structure
  5. It is a best choice when frequent search operation is involved
  6. It doesn’t allow duplicate that makes it ideal for storing unique elements

 

Constructors of HashSet

There are 4 constructors in HashSet:

1) HashSet()

It is a default constructor that creates an empty Set with a default capacity of 16 elements and having default fill ratio 0.75.

HashSet<T> obj = new HashSet<>() :

Fill ratio/ Load Factor : It simply means after which ratio/ percentage, a new set should be created. For instance, if fill ratio is 0.75, then a new hashSet would be created after occupying 75% capacity of the set.

2) HashSet(int initialCapacity)

It creates an empty set with the provided initial capacity value with default fill ratio 0.75.

HashSet<T> h = new HashSet<>(int initialCapacity);

3) HashSet<T>(int initialCapacity, float loadFactor)

It creates an empty set with provided initial capacity and load factor.

HashSet<T> h = new HashSet<T>(int initialCapacity, float loadFactor);

4) HashSet<T>(Collection obj)

It creates a set with the collection elements passed in the constructor. It can be arrayList, linkedList or any other object that implements collection interface.

HashSet<T> h = new HashSet<T>(Collection obj);

Program to demonstrate creation of HashSet in Java

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        set.add("Duplicate");
        set.add("Duplicate");
        System.out.println(set);
    }
}

Output:

[Example, Duplicate, Programmerbay]

 

How HashSet or HashMap works in Java?

HashSet internally uses the HashMap constructor to create an empty set with a default capacity of 16 and 0.75 load factor.
When the add() method is called, again put() method of HashMap is also invoked where the element that is being added acts as a key and a constant value (PRESENT) acts as a value. When one tries to add the same element then, we all know, what would happen when one tries to add an element with the same key in a map, it would override or replace the existing key-value pair. That is why HashSet doesn’t allow duplicate elements.

Further, lets see the working of HashMap.

HashMap also adheres HashTable Alogrithm Internally.

When a HashMap object is created, JVM creates Hash Table which is nothing but an array of nodes or buckets internally concerning the capacity of the Set or Map. These buckets act as a node that connects like a linked list.
When an element is added or put in the object, a corresponding hashcode or hash is generated using hashCode() method.

Based on the Modular operator it identifies the index and stores the data in that bucket (consisting array of nodes) residing on that position.
If two elements are having same hashcode, then it would not directly be stored in the same bucket, instead, the equal() method will be used to check whether the two elements are the same or not. If both are evaluated as different, then it would be stored in the same bucket otherwise, it will be replaced.

The situation of having the same hash of two elements is also known as Hashing collision, to deal with it, the equals() method is internally used by JVM.

Methods in HashSet

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

Sandeep Verma

Published by
Sandeep Verma
Tags: collection Collection interface Hash Table HashSet HashSet class java java program Set Set interface