0

Was trying to understand the internal working of HashSet when Class objects are used as elements of the set. Here is what i have done => Code <=. Found that the Object id are same for all the values in the map.

Variable What does this mean ? Shouldn't they be different, as i have created new instances of Class Element ?

2 Answers2

3

A HashSet is backed by an internal HashMap, where the keys are the Set's elements and the values are all references to the same dummy object. Therefore all the values you see in the map refer to the same object.

For example, see the implementation of add() :

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

Where PRESENT is :

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

Shouldn't they be different, as i have created new instances of Class Element ?

Only the keys should be different.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

You can check here:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/util/HashSet.java#HashSet

HashSet is implemented using HashMap :

private static final Object PRESENT = new Object();

For every put of a key-value pair, there is always same object inserted as value for every key, therefore there is always same id of the object which is PRESENT. Although you have put a new key but value of every entry in the map would be same.

Check these blogs:

http://www.java67.com/2014/01/how-hashset-is-implemented-or-works-internally-java.html

http://javahungry.blogspot.com/2013/08/how-sets-are-implemented-internally-in.html

Shweta Gulati
  • 566
  • 1
  • 7
  • 17