User913 User913 - 2 months ago 6
Java Question

Same Object id in Java Map

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 ?

Answer

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.

Comments