Java containsAll在给定列表时不返回true [英] Java containsAll does not return true when given lists
问题描述
我想检查一个数组是另一个数组的子集。
I want to check an array is subset of another array.
该程序打印错误,但我希望是真的。为什么不是containsAll返回true?
The program prints false, but I expect true. Why isn't containsAll returning true?
int[] subset;
subset = new int[3];
subset[0]=10;
subset[1]=20;
subset[2]=30;
int[] superset;
superset = new int[5];
superset[0]=10;
superset[1]=20;
superset[2]=30;
superset[3]=40;
superset[4]=60;
HashSet sublist = new HashSet(Arrays.asList(subset));
HashSet suplist = new HashSet(Arrays.asList(superset));
boolean isSubset = sublist.containsAll(Arrays.asList(suplist));
System.out.println(isSubset);
推荐答案
有一个微妙的错误:
new HashSet(Arrays.asList(subset));
上面的行不创建一组整数,因为你可能有预期。相反,它使用单个元素子集
数组创建 HashSet< int []>
。
The above line does not create a set of integers as you might have expected. Instead, it creates a HashSet<int[]>
with a single element, the subset
array.
这与泛型不支持基本类型的事实有关。
This has to do with the fact that generics don't support primitive types.
你的编译器会告诉你的如果您将子列表
和 suplist
声明为 HashSet< Integer> $ c $,则会出现错误c>。
Your compiler would have told you about the mistake if you declared sublist
and suplist
as HashSet<Integer>
.
除此之外,你还有 suplist
和子列表
containsAll()
调用中的错误方法。
On top of that, you got suplist
and sublist
the wrong way round in the containsAll()
call.
以下按预期方式工作:
Integer[] subset = new Integer[]{10, 20, 30};
Integer[] superset = new Integer[]{10, 20, 30, 40, 60};
HashSet<Integer> sublist = new HashSet<Integer>(Arrays.asList(subset));
HashSet<Integer> suplist = new HashSet<Integer>(Arrays.asList(superset));
boolean isSubset = suplist.containsAll(sublist);
System.out.println(isSubset);
一个关键变化是使用 Integer []
代替 int []
。
One key change is that this is using Integer[]
in place of int[]
.
这篇关于Java containsAll在给定列表时不返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!