Reputation:
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')
Upvotes: 1
Views: 745
Reputation: 2781
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};
Upvotes: 3
Reputation: 1004
In the second snippet you were trying to assign the type int
to Integer
type.
Autoboxing only happens for a single element (for example for one element of int to Integer).
So the Arrays.asList()
cannot be used to convert all the elements from int
to Integer
.
Reference [link][1]
Upvotes: 0
Reputation: 5516
The code Arrays.asList(nums)
won't translate to an ArrayList
with 2 values, viz. 1 and 2. It just has one value, int[] { 1, 2 }
. In order to create the right ArrayList
, you should use
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
Upvotes: 0