Internal Working of Hashset

Hashset internally use HashMap.

Key -> Input Value

Value -> Default PRESENT object

public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
private transient HashMap<E,Object> map;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

/**
* Constructs a new, empty set; the backing {@code HashMap} instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}




import java.util.HashSet;
  
class Test
{    
    public static void main(String args[]) 
    {
        // creating a HashSet
        HashSet hs = new HashSet();
          
        // adding elements to hashset
        // using add() method
        boolean b1 = hs.add("Test");
        boolean b2 = hs.add("Test1");
          
        // adding duplicate element
        boolean b3 = hs.add("Test");
          
        // printing b1, b2, b3
        System.out.println("b1 = "+b1);
        System.out.println("b2 = "+b2);
        System.out.println("b3 = "+b3);
          
        // printing all elements of hashset
        System.out.println(hs);
              
    }
}
Output:

b1 = true
b2 = true
b3 = false
[Test, Test1]

Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

Junit Mockito and Power Mockito

Important Linux Commands