HashSet对于整数类型的contains方法不起作用

4

我不理解为什么 contains 方法不起作用(实际上,如果我传入自定义类,我可以重新检查我的哈希码和相等方法,但这是 Integer 类型)。那么,除了 contains 方法外,我应该使用什么?请帮忙。

Set<Integer> st = new HashSet<>();
st.add(12);
Set<Integer> st1 = new HashSet<>();
st1.add(12);
System.out.println(st.contains(st1));

混淆是由于contains方法期望一个Object,而不是一个Integer所引起的。因此,根本原因与这个有关:https://dev59.com/DnVD5IYBdhLWcg3wDXJ3 - Marco13
st.contains(st1) 检查 st 是否包含对象 st1(即 Set<Integer>),但您只是将 12 添加到了它,而不是添加 st1 - liquid_code
2个回答

8
st.contains(st1)返回false,因为st1的类型(Set<Integer>)与st中元素的类型(Integer)不同。但是,您可以使用Set#containsAll(Collection<?>)方法:
System.out.println(st.containsAll(st1));

这将检查st1的元素是否存在于st中。


5

st1 是一个 HashSet 而不是一个 Integer

用以下代码试试,你会发现它能够工作:

Set<Integer> st = new HashSet<>();
st.add(12);
System.out.println(st.contains(12));

或者

public static void main(String[] args) {
    Set<Integer> st = new HashSet<>();
    st.add(12);
    Set<Integer> st1 = new HashSet<>();
    st1.add(12);
    System.out.println(st.containsAll(st1));
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接