为什么removeAll(Collection<?> a)
集合内的对象没有被删除时返回true?我为我的自定义对象覆盖了 hashcode 和 equals 方法。输入中对象的哈希码与选择内对象的哈希码相同。
private void onRemove(IStructuredSelection selection) {
boolean removeAll = getInput().removeAll(selection.toList()); // returns true
Set<ReadingNodeCfg> input = getInput(); // Object from selection is still there
}
输入中的对象与选择中的对象相同,那他为什么不删除呢?
此致
edit1:我通过eclipse生成equals和hashcode,getInput()返回a HashSet<ReadingNodeCfg>
,selection.toList()返回aList<ReadingNodeCfg>
编辑2:
for (Object object : selection.toList()) {
boolean remove = getInput().remove(object); // returns false
int hashCode = object.hashCode(); // returns 1130504316
int hashCode2 = getInput().iterator().next().hashCode(); // returns 1130504316
boolean equals = object.equals(getInput().iterator().next()); // returns true
}
edit3:我现在使用的是 IObservableList。现在效果很好!
修改后输入中的哈希码发生了变化。我想删除的对象与修改后的输入对象具有相同的哈希码,但无论如何它没有工作,我仍然不知道为什么。
解决方案:
好吧,我现在解决了这个问题。我为遇到相同问题的任何其他人创建了一个示例。
@Test
public void derp() {
Person person = new Person();
person.name = "jay";
Set<Person> humans = new HashSet<>();
humans.add(person);
person.name = "fred";
assertTrue(!humans.remove(person));
}
person
修改后无法删除此对象。哈希集本身无法找到对象的哈希码person
。
- 哈希码
person
:1337 - 将其添加到 Hashcode 将在此 hashcode 和对象之间创建类似引用
- 更改人名将更改哈希码:1338
- 从哈希码中删除此对象将尝试删除哈希码为 1337 的对象,这将不起作用
- 如果您不覆盖 quals/hashcode,您将能够毫无问题地删除此项目
此致