Java primitive List.contains array not working properly

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

false is displayed. 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)); 

is true?

+6
source share
2 answers

Arrays.asList(int[]) will return List<int[]> , so the output is false .

The reason for this behavior is hidden in the signature of the Arrays.asList() method. it

 public static <T> List<T> asList(T... a) 

varargs, inside, is an array of objects (ot type T ). However, int[] does not meet this definition, therefore int[] considered as one separate object.

Meanwhile, Integer[] can be thought of as an array of objects of type T because it contains objects (but not primitives).

+5
source

Arrays.asList(array) converts a int[] to List<int[]> having one element (input array). Therefore, this list does not contain 1.

On the other hand, System.out.println(Arrays.asList(array).contains(array)); will print true for the first code fragment.

+3
source

Source: https://habr.com/ru/post/987754/


All Articles