简体   繁体   中英

Java Array to List Issue

I have following Java code,

int a[] = new int[] {20, 30} ;
List lis = Arrays.asList(a) ;
System.out.print(lis.contains(20));

However, output is false. Can anybody help me, why this is not giving True ?

What you get is not a list of integers but a list of integer arrays, ie List<int[]> . You can't create collections (like List ) of primitive types.

In your case, the lis.contains(20) will create an Integer object with the value 20 and compare that to the int array, which clearly isn't equal.

Try changing the type of the array to Integer and it should work:

Integer a[] = new Integer[] {20, 30} ;
List lis = Arrays.asList(a) ;
System.out.print(lis.contains(20));

The static method asList uses as parameter varargs: ... . Only by requiring <Integer> you prevent a List<Object> where a is an Object.

int[] a = new int[] {20, 30} ;
List<Integer> lis = Arrays.asList(a) ;
System.out.print(lis.contains(20));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM