问题
I want to check an array is subset of another array.
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);
回答1:
There is a subtle bug in:
new HashSet(Arrays.asList(subset));
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.
Your compiler would have told you about the mistake if you declared sublist
and suplist
as HashSet<Integer>
.
On top of that, you got suplist
and sublist
the wrong way round in the containsAll()
call.
The following works as expected:
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);
One key change is that this is using Integer[]
in place of int[]
.
回答2:
Leaving aside your initialisation issues (as identified by NPE), you've mixed up your two sets and you actually want:
boolean isSubset = suplist.containsAll(Arrays.asList(sublist));
i.e. does {10,20,30,40,60}
contain {10,20,30}
? (which, of course, it does)
来源:https://stackoverflow.com/questions/15664396/java-containsall-does-not-return-true-when-given-lists