Why when I use this code,
int[] array = new int[3];
array[0] = 0;
array[1] = 1;
array[2] = 2;
System.out.println(Arrays.asList(array).contains(1));
it outputs false. But when I use this code,
Integer[] array = new Integer[3];
array[0] = 0;
array[1] = 1;
array[2] = 2;
System.out.println(Arrays.asList(array).contains(1));
it outputs true?
Primitive data types cannot be stored in ArrayList but can be in Array.
contains() method in Java? The ArrayList. contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it.
It's a shame, there is no primitive list. Large data sets should always be hold as primitives...
Arrays.asList(int[])
will return a List<int[]>
, which is why the output is false
.
The reason for this behavior is hidden in the signature of the Arrays.asList()
method. It's
public static <T> List<T> asList(T... a)
The varargs, internally, is an array of objects (ot type T
). However, int[]
doesn't match this definition, which is why the int[]
is considered as one single object.
Meanwhile, Integer[]
can be considered as an array of objects of type T
, because it comprises of objects (but not primitives).
Arrays.asList(array)
converts an int[]
to a List<int[]>
having a single element (the input array). Therefore that list doesn't contain 1.
On the other hand, System.out.println(Arrays.asList(array).contains(array));
will print true for the first code snippet.
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