HashSet in Java

Video Tutorial
FREE
HashSet Introduction thumbnail
This video belongs to
Java DSA Course - Master the Fundamentals and Beyond
12 modules
Certificate

Overview

A HashSet is an unsorted and unordered Set in Java. HashSet in Java does not maintain the insertion order and the elements are inserted on the basis of their hashcode values. Hence, the more efficient your hashCode() implementation, the faster will be the search operations.

HashSet class is used when a collection with no duplicate entries is needed and you don’t care about the order of the elements when you iterate through it. Mostly when an element has to be accessed randomly, HashSet is used.

Java HashSet Features

A HashSet has the following properties:

  • It allows storing only one null value.
  • The elements are stored using the hashing mechanism.
  • HashSet class is non-synchronized.
  • Elements are inserted into the hash table using their hashcodes.
  • It contains unique elements only.
  • It is useful for search operations.
  • The data structure used is a hash table.

Declaration of HashSet in Java

The HashSet in Java is declared using the following syntax:

Syntax:

Example:

where carData is an instance of HashSet class and stores only String values.

Java HashSet Example

Output:

Explanation:

  • The above example shows how to declare and add elements to an instance of HashSet class.
  • As you can observe, the order of elements in the output is not the same as the insertion order.

Hierarchy of HashSet Class

Hierarchy of HashSet class

The HashSet class implements the Set interface and extends the AbstractSet in Java. The Set interface extends the Collection interface which further inherits from the Iterable interface.

Constructors of Java HashSet

It is worth mentioning here that the default capacity of HashSet is 16 and the load factor is 0.75.

The following table mentions the various constructors of HashSet class:

Constructor NameDescription
HashSet()It is the default constructor of HashSet class which initializes a HashSet object with default capacity and load factor.
HashSet(int capacity)It constructs a HashSet with capacity equal to the given argument. The HashSet can grow automatically as more elements are added.
HashSet(int capacity, int loadFactor)It constructs a HashSet with capacity and load factor equal to the given capacity and load factor arguments.
HashSet(Collection c)It constructs a HashSet and initializes it with elements from the given Collection c.

Methods of Java HashSet

These are different methods used for performing various operations on the HashSet.

Type of ModifierMethod NameDescription of the MethodTime Complexity
booleanadd(E e)This method adds an element of type E if and only if it is not already present in the HashSet.O(1)
voidclear()It clears the entire HashSet by removing all the elements present in it.O(1)
Objectclone()This method creates and returns a shallow copy of the HashSet instance where the individual elements of the HashSet are not cloned.O(N)
booleancontains(Object e)It returns false if the specified element is not present in the HashSet else it returns true.O(1)
booleanisEmpty()It returns true if the HashSet is empty, otherwise false.O(1)
Iterator<E>iterator()It returns an iterator over all the values present in the HashSet.O(N)
booleanremove(Object e)It removes the Object e if it is present in the HashSet.O(1)
intsize()It returns the number of elements present in the HashSet.O(1)

Performing Various Operations on HashSet

1. Iterating through the HashSet

In this example, we will iterate over the HashSet and print its elements.

Code:

Output:

Explanation:

  • In the example above, a HashSet studentData is created to store objects of Student class.
  • Student objects s1, s2 and s3 are inserted into the HashSet in this same order.
  • However, as you can observe the order of objects in the output is NOT the same as the insertion order.

2. Removing Elements from HashSet in Java

To remove the elements of a HashSet, remove() method is used. It checks if the data to be removed is preset in the HashSet or not. If it is present, it removes the data and the size of the HashSet in decremented by one.

Output:

3. Ignoring Duplicate Elements in Java Hashset

  • HashSet uses the hashcode values of elements and the equals() method to check if two elements/objects are identical or not.
  • Two identical elements cannot be inserted into a HashSet.

Example:

Output:

Explanation:

  • In the above example, it can be observed that objects s2 and s1 are equal to each other as per the implementation of equals() method in the Student class and both s1 and s2 objects have same hashcodes.
  • Hence, when s2 is added to the HashSet using the add() method, the HashSet ignores it.

4. Create HashSet from a Collection

You can use the HashSet(Collection c) constructor to initialize a HashSet using an existing Collection such as ArrayList, Vector, etc.

Example:

Output:

Explanation:

  • In the example above, the HashSet hset is initialized with the list elements.
  • As you can observe, though the ArrayList list contains 2 twice, it comes up only once in the HashSet. It is because the HashSet does not contain duplicate elements.
  • Finally, another element 5 is added to the hset and then it is printed using the iterator itr.

Conclusion

  1. HashSet is an unordered Collection that extends the AbstractSet class and implements the Set interface.
  2. HashSet inserts objects on the basis of their hashcodes. Duplicate elements cannot be inserted into a HashSet.
  3. The default value of capacity and load factor are 16 and 0.75 respectively.
  4. HashSet uses Hash Table for internal storage of its elements on the basis of their hashcodes.
  5. HashSet does not maintain the insertion order of its elements.
  6. There are various methods and constructors available for performing different operations on a HashSet.
    • add(E e)- adds an element
    • remove(E)- removes an element if present
    • clear() - deletes all elements of a HashSet
    • clone()- creates a shallow copy of a HashSet
    • isEmpty() - checks if HashSet is empty or not
    • size()- gives number of elements present in a HashSet
    • iterator()- returns an iterator over the elements of a HashSet

See More