Java Collections Java
Let's try to use Arrays.asList() with primitive array:
package com.logicbig.example;
import java.util.Arrays;
import java.util.List;
public class ArraysAsListForPrimitives {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
List<Integer> list = Arrays.asList(numbers);
}
}
Error:(10, 44) java: incompatible types: inference variable T has incompatible bounds
equality constraints: java.lang.Integer
lower bounds: int[]
Why it failed?
Let's see signature of Arrays.asList() method
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
As seen above Arrays.asList() accept generic type T. Since Java generics work only on reference types (object types), not on primitives, our above example failed.
Since int[] as a whole is an object it can be added as a single element:
package com.logicbig.example;
import java.util.Arrays;
import java.util.List;
public class ArraysAsListForPrimitives {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
List<int[]> list = Arrays.asList(numbers);
System.out.println(list);
}
}
[[I@1d81eb93]
How to fix it?
By using Arrays.setAll() method
package com.logicbig.example;
import java.util.Arrays;
import java.util.List;
public class ArraysAsListForPrimitives2 {
public static void main(String[] args) {
int[] numbers ={1, 2, 3} ;
Integer[] boxed = new Integer[numbers.length];
Arrays.setAll(boxed, i -> numbers[i]);
List<Integer> list = Arrays.asList(boxed);
System.out.println(list);
}
}
[1, 2, 3]
By adding each element manually
package com.logicbig.example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArraysAsListForPrimitives3 {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
List<Integer> list = new ArrayList<>();
Arrays.stream(numbers).forEach(list::add);
System.out.println(list);
}
}
[1, 2, 3]
By using IntStream#boxed() method
package com.logicbig.example;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ArraysAsListForPrimitives4 {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
List<Integer> list = Arrays.stream(numbers).boxed().collect(Collectors.toList());
System.out.println(list);
}
}
[1, 2, 3]
|