我正在尝试学习 Java,并且我达到了 HashSet 部分,长话短说,我正在测试 contain 方法。
public static void main(String[] args) {
HashSet<Integer> firstSet = new HashSet<>();
firstSet.add(3);
HashSet<Integer> secondSet = new HashSet<>();
secondSet.add(3);
boolean var = firstSet.contains(secondSet);
System.out.println(var);
}
我相信这段代码应该返回 true,而它返回 false。任何帮助!
最佳答案
让我们看看docs 包含
:
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that
(o==null ? e==null : o.equals(e))
.
因为我们都知道这里没有空值,所以我们可以说如果 o.equals(e)
contains
将返回 true。
o
是你传递给contains
的参数,它是一个HashSet
。 e
是第一个集合的元素,应该是一个Integer
。由于 Integer
和 HashSet
是不相关的类型,因此它们相等的可能性很小。
你似乎在这里犯了一个逻辑错误。要检查一个集合是否是另一个集合的超集,请调用 containsAll
相反:
Returns true if this collection contains all of the elements in the specified collection.
关于java - HashSet.contains 返回 false 而它不应该返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47722110/