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?
Because the
HashSetcontract specifies thatremove()returntrueif the specified object existed and was removed. To do this, it uses the wrappedHashMap#remove()which returns the removed value.If you were to store
nullinstead of an object, then the call toHashMap#remove()would returnnull, which would be indistinguishable from the result of attempting to remove a non-existent object, and the contract ofHashSet.remove()could not be fulfilled.