In the Java API, the implementation of HashSet is using an Object as a value for the inside HashMap,
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
but HashMap allows its value is null. I think that's not necessary to fill the value, so why is this needed?
All Contents are copyrighted and must not be reproduced in any form. * This class provides custom implementation of HashSet (without using java api's- we will be using HashMapCustom)- which allows does not allow you to store duplicate values. * Note- implementation does not allow you to store null values.
Where key is the object we have passed and the value is another object, called PRESENT. It is a constant in java.util.HashSet. We are achieving uniqueness in Set internally through HashMap. When we create an object of HashSet, it will create an object of HashMap.
HashSet (): It is used to create an instance of the HashSet class that is empty and uses the default equality comparer for the set type.
We can observe that duplicate values are not stored in the HashSet. When we pass duplicate elements in the add () method of the Set object, it internally returns false. Here, a question arises that how it returns false. When we open the HashSet implementation of the add () method in Java APIs i.e. rt.jar, we find the following code in it:
Because the HashSet
contract specifies that remove()
return true
if the specified object existed and was removed. To do this, it uses the wrapped HashMap#remove()
which returns the removed value.
If you were to store null
instead of an object, then the call to HashMap#remove()
would return null
, which would be indistinguishable from the result of attempting to remove a non-existent object, and the contract of HashSet.remove()
could not be fulfilled.
but HashMap allows its value is null
Why would that matter, when the value is entirely controlled by HashSet
? That ensures that the only value ever associated with a key is PRESENT
. So if map.put
returns null
, that could only be because there was previously no entry for that key.
The value is just there because some value has to be specified, and if the value were specified as null
, that would be bad - it would make it harder to tell whether there was a value before the call to add
. If you're going to specify any non-null value, you might as well force it to be the same value all the time - you wouldn't want it to hold up garbage collection, for example.
Now if you're asking why HashSet
is implemented in terms of HashMap
rather than being a more efficient implementation which doesn't record a value at all, that's a different question, and one I don't have an answer to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With