1.

How Hashset Store Elements?

Answer»

You must know that HASHMAP store key-VALUE pairs, with one condition i.e. keys will be unique. HashSet uses Map’s this FEATURE to ensure uniqueness of elements. In HashSet class, a map declaration is as below:

private transient HashMap<E,Object> map;
//This is ADDED as value for each key
private static final Object PRESENT = NEW Object();
So when you store a element in HashSet, it stores the element as key in map and “PRESENT” object as value. (See declaration above).

public boolean add(E e)
{
return map.put(e, PRESENT)==null;
}

You must know that HashMap store key-value pairs, with one condition i.e. keys will be unique. HashSet uses Map’s this feature to ensure uniqueness of elements. In HashSet class, a map declaration is as below:

private transient HashMap<E,Object> map;
//This is added as value for each key
private static final Object PRESENT = new Object();
So when you store a element in HashSet, it stores the element as key in map and “PRESENT” object as value. (See declaration above).

public boolean add(E e)
{
return map.put(e, PRESENT)==null;
}



Discussion

No Comment Found