I'm wondering how I can convert a primitive array of integers to a list of Integer?
There's no compile error for:
int[] nums = {0, 1};
List<Integer> list = new ArrayList(Arrays.asList(nums));
list.get(0);
But this one:
int[] nums = {0, 1};
List<Integer> list = new ArrayList(Arrays.asList(nums));
int a = list.get(0);
fails with:
java.lang.ClassCastException: class [I cannot be cast to class java.lang.Integer ([I and java.lang.Integer are in module java.base of loader 'bootstrap')
In Java 8:
List<Integer> list = Arrays.stream(nums)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
In Java 16 and later:
List<Integer> list = Arrays.stream(nums).boxed().toList();
Note: You might need to:
import java.util.stream.Collectors;
Use for loop:
List<Integer> list = new ArrayList();
for(int n : nums) {
list.add(n);
}
Declare the original array as Integer[]
instead of int[]
:
Integer[] nums = {0, 1};