Java HashSet
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.
HashSet class declaration :
Get Rushikesh Dudhane’s stories in your inbox
Join Medium for free to get updates from this writer.
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 :
Methods of Java HashSet class :
Various methods of Java HashSet class are as follows:
Java HashSet Example :
Let’s see a simple example of HashSet. Notice, the elements iterate in an unordered collection
Output:
Example 2: ignoring duplicate elements
Output:
Guide: http://www.vevcodelab.com/








