Sitemap
Nikhil Sambhaji Salvi

Nikhil Sambhaji Salvi

Java HashSet

2 min readNov 28, 2023

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

  • HashSet stores the elements by using a mechanism called hashing.
  • HashSet contains unique elements only.
  • HashSet allows null value.
  • HashSet class is non synchronized.
  • HashSet doesn’t maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
  • HashSet is the best approach for search operations.
  • The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set :

A list can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class

The HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.

Get Nikhil Sambhaji Salvi’s stories in your inbox

Join Medium for free to get updates from this writer.

HashSet class declaration :

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

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

Constructors of Java HashSet class :

Press enter or click to view image in full size

Methods of Java HashSet class :

Various methods of Java HashSet class are as follows:

Press enter or click to view image in full size

Java HashSet Example :

Let’s see a simple example of HashSet. Notice, the elements iterate in an unordered collection

Press enter or click to view image in full size
Output

Example 2: ignoring duplicate elements

Press enter or click to view image in full size
Press enter or click to view image in full size
Output

--

--