一个元素如何不包含在原始集合中,而是包含在其未修改副本中?
原始集不包含该元素,而其副本包含该元素。 See image.
以下方法返回 true
,尽管它应该始终返回 false
。 c
和clusters
的实现都是HashSet
。
public static boolean confumbled(Set<String> c, Set<Set<String>> clusters) {
return (!clusters.contains(c) && new HashSet<>(clusters).contains(c));
}
调试显示元素是包含在原始元素中,但Set.contains(element)
出于某种原因返回false
。 See image.
有人可以向我解释一下这是怎么回事吗?
最佳答案
如果您更改 Set
中的元素(在您的情况下,元素是 Set<String>
,因此添加或删除 String 会更改它们), Set.contains(element)
可能找不到它,因为 hashCode
元素的外观将不同于元素首次添加到 HashSet
时的样子.
当您创建新的 HashSet
时包含原始元素的元素,元素是根据其当前元素添加的 hashCode
, 所以 Set.contains(element)
将为新的 HashSet
返回 true .
您应该避免将可变实例放在 HashSet
中(或将它们用作 HashMap
中的键),如果您无法避免它,请确保在改变它之前删除该元素,然后再重新添加它。否则你的HashSet
会坏掉的。
一个例子:
Set<String> set = new HashSet<String>();
set.add("one");
set.add("two");
Set<Set<String>> setOfSets = new HashSet<Set<String>>();
setOfSets.add(set);
boolean found = setOfSets.contains(set); // returns true
set.add("three");
Set<Set<String>> newSetOfSets = new HashSet<Set<String>>(setOfSets);
found = setOfSets.contains(set); // returns false
found = newSetOfSets.contains(set); // returns true
关于java - 元素存在但 `Set.contains(element)` 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30614498/