Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ArrayList of Integer Objects to an int array? [duplicate]

Possible Duplicate:
How to convert an ArrayList containing Integers to primitive int array?

I tried the code below, but it does not work. Do I have to make a loop copy the ArrayList into an array ?

int[]intArray = (int[]) integerArrayList.toArray();
like image 465
Apple Grinder Avatar asked Oct 27 '12 09:10

Apple Grinder


2 Answers

If you want primitive type array, you can use Apache Commons ArrayUtils#toPrimitive method to get primitive array from wrapper array: -

public static int[] toPrimitive(Integer[] array)

You can use it like this: -

int[] arr = ArrayUtils.toPrimitive((Integer[])integerArrayList.toArray());

Or, you can use the 1-arg version of toArray method, that takes an array and returns the array of that type only. That way, you won't have to the typecasting.

List<Integer> myList = new ArrayList<Integer>();
Integer[] wrapperArr = myList.toArray(new Integer[myList.size()]);

// If you want a `primitive` type array
int[] arr = ArrayUtils.toPrimitive(wrapperArr);

However, if you are Ok with the wrapper type array (Which certainly will not trouble you), then you don't need to do that last step.


Also, you can also create a primitive array, without having to create that intermediate Wrapper type array. For that you would have to write it through loop: -

int[] arr = new int[myList.size()];

for(int i = 0; i < myList.size(); i++) {
    if (myList.get(i) != null) {
        arr[i] = myList.get(i);
    }
}
like image 121
Rohit Jain Avatar answered Sep 25 '22 13:09

Rohit Jain


You'll need to iterate through and copy it.

int[] intArray = new int[integerArrayList.size()];
for (int i = 0; i < intArray.length; i++) {
    intArray[i] = integerArrayList.get(i);
}
like image 21
FThompson Avatar answered Sep 23 '22 13:09

FThompson