Search code examples
javaarrayscollectionsprimitiveprimitive-types

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?


Solution

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