Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.asList(int[]) not working [duplicate]

Tags:

java

arrays

list

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"); } 
like image 882
Henry Zhu Avatar asked Jul 15 '15 05:07

Henry Zhu


2 Answers

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

like image 161
Eran Avatar answered Sep 28 '22 01:09

Eran


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"); } 
like image 25
Makoto Avatar answered Sep 28 '22 03:09

Makoto