Search code examples
javaarraysarraylisttype-conversionconverters

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') 

Solution

  • 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};