HashSet

package com.gs.corejava.collections;

//Java program to demonstrate 
//internal working of HashSet 

import java.util.HashSet;

public class TestHashSet {
	public static void main(String args[]) {
		// creating a HashSet
		HashSet hs = new HashSet();

		// adding elements to hashset
		// using add() method
		boolean b1 = hs.add("RED");
		boolean b2 = hs.add("GREEN");
		boolean b3 = hs.add("BLUE");
		boolean b4 = hs.add("PINK");

		// REMOVE ELEMENT
		boolean b5 = hs.remove("RED");

		// adding duplicate element
		boolean b6 = hs.add("GREEN");

		// printing b1, b2, b3
		System.out.println("b1 = " + b1);
		System.out.println("b2 = " + b2);
		System.out.println("b3 = " + b3);
		System.out.println("b4 = " + b4);
		System.out.println("b5 = " + b5);
		System.out.println("b6 = " + b6);

		// printing all elements of hashset
		System.out.println(hs);

	}
}
b1 = true
b2 = true
b3 = true
b4 = true
b5 = true
b6 = false
[BLUE, GREEN, PINK]

Java Code :

// predefined HashSet class
public class HashSet
{
    // A HashMap object 
    private transient HashMap map;

    // A Dummy value(PRESENT) to associate with an Object in the Map
    private static final Object PRESENT = new Object();
    
    // default constructor of HashSet class
    // It creates a HashMap by calling 
    // default constructor of HashMap class
    public HashSet() {
        map = new HashMap<>();
    }

    // add method 
    // it calls put() method on map object
    // and then compares it's return value with null
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
 
    // Other methods in Hash Set
}

Now as you can see that whenever we create a HashSet, it internally creates a HashMap and if we insert an element into this HashSet using add() method, it actually call put() method on internally created HashMap object with element you have specified as it’s key and constant Object called “PRESENT” as it’s value. So we can say that a Set achieves uniqueness internally through HashMap. Now the whole story comes around how a HashMap and put() method internally works.

As we know in a HashMap each key is unique and when we call put(Key, Value) method, it returns the previous value associated with key, or null if there was no mapping for key. So in add() method we check the return value of map.put(key, value) method with null value.

  1. If map.put(key, value) returns null, then the statement “map.put(e, PRESENT) == null” will return true and element is added to the HashSet(internally HashMap).

  2. If map.put(key, value) returns old value of the key, then the statement “map.put(e, PRESENT) == null” will return false and element is not added to the HashSet(internally HashMap).

Example :

Last updated