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);

	}
}

Java Code :

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

Was this helpful?