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

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

Leave a Comment