Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

java - Null Object in HashSet implementation

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...