Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java primitive array List.contains does not work as expected

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?

like image 549
Chris Smith Avatar asked May 22 '15 14:05

Chris Smith


People also ask

Can an ArrayList contain primitives?

Primitive data types cannot be stored in ArrayList but can be in Array.

Does array have Contains method in Java?

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​.

Can list contain primitive types?

It's a shame, there is no primitive list. Large data sets should always be hold as primitives...


2 Answers

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

like image 187
Konstantin Yovkov Avatar answered Nov 09 '22 23:11

Konstantin Yovkov


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.

like image 40
Eran Avatar answered Nov 10 '22 00:11

Eran