Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array to List Issue

Tags:

java

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 ?

like image 972
Arpssss Avatar asked Apr 27 '12 16:04

Arpssss


People also ask

Can we convert array to list in java?

Since List is a part of the Collection package in Java. Therefore the Array can be converted into the List with the help of the Collections. addAll() method.

How do you make an array into a list?

array objects can be converted to a list with the tolist() function. The tolist() function doesn't accept any arguments. If the array is one-dimensional, a list with the array elements is returned. For a multi-dimensional array, a nested list is returned.

How do you add an int array to an ArrayList in java?

Using ArrayList. add() method to manually add the array elements in the ArrayList: This method involves creating a new ArrayList and adding all of the elements of the given array to the newly created ArrayList using add() method.


2 Answers

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));
like image 91
Thomas Avatar answered Oct 09 '22 07:10

Thomas


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));
like image 34
Joop Eggen Avatar answered Oct 09 '22 05:10

Joop Eggen