user14488711
user14488711

Reputation:

Converting primitive array of int into ArrayList in Java: "java.lang.ClassCastException: [I cannot be cast to java.lang.Integer"

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

Answers (3)

Positive Navid
Positive Navid

Reputation: 2781

Solution 1:

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;

Solution 2:

Use for loop:

List<Integer> list = new ArrayList();
for(int n : nums) {
    list.add(n);
}

Solution 3:

Declare the original array as Integer[] instead of int[]:

Integer[] nums = {0, 1};

Upvotes: 3

Kesava Karri
Kesava Karri

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]

[1]: https://www.baeldung.com/java-primitive-array-to-list#:~:text=Unfortunately%2C%20this%20won%E2%80%99t,to%20Integer%5B%5D).

Upvotes: 0

devang
devang

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

Related Questions