Search code examples
javaarraysgenericscollections

How to create ArrayList (ArrayList<Integer>) from array (int[]) in Java


I have seen the question: Create ArrayList from array

However when I try that solution with following code, it doesn't quite work in all the cases:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class ToArrayList {

    public static void main(String[] args) {
        // this works
        String[] elements = new String[] { "Ryan", "Julie", "Bob" };
        List<String> list = new ArrayList<String>(Arrays.asList(elements));
        System.out.println(list);

        // this works
        List<Integer> intList = null;
        intList = Arrays.asList(3, 5);
        System.out.println(intList);

        int[] intArray = new int[] { 0, 1 };
        // this doesn't work!
        intList = new ArrayList<Integer>(Arrays.asList(intArray));
        System.out.println(intList);
    }
}

What am I doing wrong here? Shouldn't the code intList = new ArrayList<Integer>(Arrays.asList(intArray)); compile just fine?


Solution

  • The problem in

    intList = new ArrayList<Integer>(Arrays.asList(intArray));
    

    is that int[] is considered as a single Object instance since a primitive array extends from Object. This would work if you have Integer[] instead of int[] since now you're sending an array of Object.

    Integer[] intArray = new Integer[] { 0, 1 };
    //now you're sending a Object array
    intList = new ArrayList<Integer>(Arrays.asList(intArray));
    

    From your comment: if you want to still use an int[] (or another primitive type array) as main data, then you need to create an additional array with the wrapper class. For this example:

    int[] intArray = new int[] { 0, 1 };
    Integer[] integerArray = new Integer[intArray.length];
    int i = 0;
    for(int intValue : intArray) {
        integerArray[i++] = intValue;
    }
    intList = new ArrayList<Integer>(Arrays.asList(integerArray));
    

    But since you're already using a for loop, I wouldn't mind using a temp wrapper class array, just add your items directly into the list:

    int[] intArray = new int[] { 0, 1 };
    intList = new ArrayList<Integer>();
    for(int intValue : intArray) {
        intList.add(intValue);
    }