Skip to content

Java ArrayList to Array Example

Java ArrayList to Array example shows how to convert ArrayList to array in Java. ArrayList to array example also shows how to convert ArrayList to array of primitive values.

Java ArrayList is a part of the Java Collection framework.

How to convert ArrayList to array?

There are a couple of ways using which you can convert ArrayList to array in Java.

1) Using for loop

Probably this is the simplest way. Loop through the ArrayList elements using for loop and assign elements to an array as given below.

Output

2. Using the toArray method

The ArrayList class has toArray method which can be used for the conversion.

Please note that this method returns an array of Objects. You need to cast array elements to the appropriate type before using it.

There is an overloaded method toArray which accepts an array as given below.

This method returns an array containing all the elements of the ArrayList. The returned array is of the same type which is specified in the argument array.

Example

Output

There is no restriction on the size of the array specified as toArray method argument. You can even specify an empty array. However, If the argument array has size less than the size of the ArrayList, a new array of the same type is created and returned. If the argument array’s size is greater than the size of the list, the array element that comes immediately after the ArrayList elements is set to null to mark the end of the ArrayList elements.

Output

It is always best practice to specify the array with the same or larger size to reduce the additional overhead of creating a new array.

3) Using Apache Commons

If you are using Apache Commons library and you want to convert ArrayList having wrapper class objects to an array of equivalent primitive values, you are in luck. Use toPrimitive method of ArrayUtils class to do the conversion.

This method has been overloaded for all the primitive types.

We can use this method in conjunction with toArray method to convert ArrayList of wrapper objects to an array of primitive values as given below.

Output

This example is a part of the Java ArrayList tutorial with examples.

References:
1. ArrayList JavaDoc
2. ArrayUtils class of Apache Commons library

About the author

Leave a Reply

Your email address will not be published.