When I run the following code, no output is printed.
int[] array = {3, 2, 5, 4}; if (Arrays.asList(array).contains(3)) { System.out.println("The array contains 3"); }
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>
.
In Java 8, you don't need to convert the array at all; just turn it into a stream via Arrays#stream
, then use the anyMatch
predicate to see if the value you want is contained in the array.
int[] array = {3, 2, 5, 4}; if (Arrays.stream(array).anyMatch(x -> x == 3)) { System.out.println("The array contains 3"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With