问题描述
HashSet是使用HashMap实现的,当我们向HashSet添加任何e1时,如果e1不在集合中,它会在HashMap中添加(e1,new Object())。我的问题是为什么他们插入新的Object(),当他们可以插入像(e1,null),这是更优化的方法,因为没有创建新的对象。在这里插入空值有什么缺点吗?
HashSet is implemented using HashMap and when we add anything say e1 to HashSet, internally it adds (e1,new Object()) in the HashMap if e1 was not present in the set. My question is why they are inserting new Object(), when they could have inserted like (e1,null), which is more optimized approach as no new Objects are created. Is there any downside to inserting nulls here?
推荐答案
A HashSet
不每次新密钥将
添加到地图中时,都不会添加新的对象
。它确实使用 Object
,但每次都使用相同的 Object
。此值在 HashSet
源代码中命名为 PRESENT
。
A HashSet
doesn't add a new Object
each time a new key is put
into the map. It does use an Object
, but it uses the same Object
each time. This value is named PRESENT
in the HashSet
source code.
add
方法在内部 HashMap上调用
。 put(key,PRESENT)
remove
方法在内部 HashMap
remove(key) >,但它必须返回 boolean
,指示密钥是否存在。如果将 null
存储为值,那么 HashSet
将需要调用 containsKey
首先,然后删除
,以确定密钥是否存在 - 额外开销。在这里,只有一个 Object
的内存开销,这是非常小的。
The add
method calls put(key, PRESENT)
on the internal HashMap
. The remove
method calls remove(key)
on the internal HashMap
, but it must return a boolean
indicating whether the key was present. If null
were stored as the value, then the HashSet
would need to call containsKey
first, then remove
, to determine if the key was present -- additional overhead. Here, there is only the memory overhead of one Object
, which is quite minimal.
这篇关于为什么HashSet的内部实现会创建虚拟对象以在HashMap中作为值插入而不是插入空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!