为什么不从套装中删除? [英] Why won't it remove from the set?
问题描述
这个错误花了我一段时间才找到...
This bug took me a while to find...
考虑这个方法:
public void foo(Set<Object> set)
{
Object obj=set.iterator().next();
set.remove(obj)
}
我用一个方法调用方法非空哈希集,但不会删除任何元素!
I invoke the method with a non-empty hash set, but no element will be removed!
为什么会这样?
推荐答案
对于HashSet,如果对象的hashCode在添加到集合后发生更改,则会发生这种情况。然后HashSet.remove()方法可能会查找错误的Hash存储桶而无法找到它。
For a HashSet, this can occur if the object's hashCode changes after it has been added to the set. The HashSet.remove() method may then look in the wrong Hash bucket and fail to find it.
如果你执行了iterator.remove(),这可能不会发生,但无论如何,将对象存储在hashCode可以更改的HashSet中是一个等待发生的事故(正如您所发现的那样)。
This probably wouldn't happen if you did iterator.remove(), but in any case, storing objects in a HashSet whose hashCode can change is an accident waiting to happen (as you've discovered).
这篇关于为什么不从套装中删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!