Internal working of Set/HashSet in Java

JavaObject Oriented ProgrammingProgramming

Set data structure is used to store unique values only, meaning no duplicate values would be stored in a set. When a HashSet is created, it internally implements a HashMap. An element can be inserted into the HashSet using the ‘add’ function. This internally calls the ‘put’ function since a HashMap would have been internally created. Hence, Set takes in unique values with the help of HashMap.

HashMap contains unique key and value pairs, wherein the key and value pairs are inserted using the ‘put’ function. Upon calling the ‘put’ function, a previous value associated with the key or null is returned depending on whether a mapping is present for the key or not.

LinkedHashSet extends to the HashSet class, meaning LinkedHashSet calls the constructors of HashSet class using the ‘super’ function.


 Live Demo

import java.util.HashSet;
public class Demo{
   public static void main(String args[]){
      HashSet my_hashset = new HashSet();
      boolean my_b1 = my_hashset.add("only");
      boolean my_b2 = my_hashset.add("sample");
      boolean my_b3 = my_hashset.add("sample");
      System.out.println("The value of first boolean is " + my_b1);
      System.out.println("The value of second boolean is = "+my_b2);
      System.out.println("The value of third boolean is = "+my_b3);


The value of first boolean is true
The value of second boolean is = true
The value of third boolean is = false
[only, sample]

A class named Demo contains the main function where an instance of HashSet is defined. Elements are added into the hashset using the ‘add’ function. These elements are then displayed on the screen.

Published on 04-Jul-2020 08:38:07