HashSet实现中的Null对象 [英] Null Object in HashSet implementation

查看:310
本文介绍了HashSet实现中的Null对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java API中,HashSet的实现是使用Object作为内部HashMap的值,

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;
}

但HashMap允许其值为null。我认为没有必要填写这个值,为什么需要这个呢?

but HashMap allows its value is null. I think that's not necessary to fill the value, so why is this needed?

推荐答案

因为 HashSet contract指定 remove()如果指定的对象存在并被删除,则返回 true 。为此,它使用包装的 HashMap #remove()返回删除的值。

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.

如果你是要存储 null 而不是对象,那么对 HashMap #remove()的调用将返回 null ,与尝试删除不存在的对象的结果无法区分,并且 HashSet.remove()的合同可以不履行。

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.

这篇关于HashSet实现中的Null对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆