Arpssss
Arpssss

Reputation: 3858

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 ?

Upvotes: 9

Views: 270

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109557

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

Upvotes: 1

Thomas
Thomas

Reputation: 88707

What you get is not a list of integers but a list of integer arrays, i.e. 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));

Upvotes: 13

Related Questions