When you pass an array of primitives (int[]
in your case) to Arrays.asList
, it creates a List<int[]>
with a single element – the array itself. Therefore contains(3)
returns false. contains(array)
would return true.
If you’ll use Integer[]
instead of int[]
, it will work.
Integer[] array = {3, 2, 5, 4};
if (Arrays.asList(array).contains(3))
{
System.out.println("The array contains 3");
}
A further explanation :
The signature of asList
is List<T> asList(T...)
. A primitive can’t replace a generic type parameter. Therefore, when you pass to this method an int[]
, the entire int[]
array replaces T
and you get a List<int[]>
. On the other hand, when you pass an Integer[]
to that method, Integer
replaces T
and you get a List<Integer>
.