[英]HashSet contains not working for Integer
我不明白为什么包含不起作用(实际上如果我已经通过自定义类我可以重新访问我的hascode和equals方法,但这是Integer)。 那么代替包含我可以使用的东西? 请帮忙。
Set<Integer> st = new HashSet<>();
st.add(12);
Set<Integer> st1 = new HashSet<>();
st1.add(12);
System.out.println(st.contains(st1));
st.contains(st1)
返回false
,因为st1
的类型( Set<Integer>
)与st
中的元素类型( Integer
)不同。
但是,您可以使用Set#containsAll(Collection<?>)
方法:
System.out.println(st.containsAll(st1));
这将检查st1
中的元素是否存在于st
。
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.