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 ?
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.
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.
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.
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));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With