Java containsall does not return true when a list is given

I want to check that one array is a subset of another

The program prints incorrectly, but I hope it is true Why not include all the returned truths?

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);

Solution

There is a subtle mistake:

new HashSet(Arrays.asList(subset));

The above line does not create a set of integers as you would expect Instead, it creates a HashSet < int [] > using a single element, subset array

This is related to the fact that generics do not support basic types

If you declare sublist and superlist as HashSet < integer >, the compiler will tell you about the error

Most importantly, you get the sublist and sublist in the wrong way in the containsall() call

The following works as expected:

Integer[] subset = new Integer[]{10,20,30};
    Integer[] superset = new Integer[]{10,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);

A key change is to use integer [] instead of int []

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>