Java primitive array List.contains does not work as expected Java primitive array List.contains does not work as expected arrays arrays

Java primitive array List.contains does not work as expected


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.