HashSet Class in java.util: hashing, hash code, types of constructors, how to create a hash set

HashSet Class: HashSet Class is used to create a hash table and implements Set interface in java.util. It extends AbstractSet class. Hash table uses a process known as hashing to store data. In this process a key is used to find a unique value. This unique value is known as hash code. Hashing is used for fast processing of operations. The only disadvantage of hashing is that it does not stores information in a sorted way.

Types of constructors in HashSet Class:

Type-1: To create a default hash set.

HashSet( )

Type-2: Create a hash set with elements of collection cl.

HashSet(Collection cl)

Type-3: Create a hash set that has size.

HashSet(int size)

Type-4: Create a hash set that has size and fill ratio. Fill ratio is used to find how full is the hash set before resizing. Value of fill ratio is between 0.0 and 1.0.

HashSet(int size, float fr)

Here’s a program to create a hash set:

import java.util.*;

class Test {

public static void main(String args[ ]) {

HashSet a = new HashSet();










[E, P, M, R, O]

Note: Output may vary as hash set does not creates a sorted set.

Leave a Reply