Java How to Convert ArrayList to Array Easily
arrayList.toArray(new Type[arrayList.size()]) to convert an ArrayList to an array in Java, for example: String[] arr = list.toArray(new String[list.size()]).Examples
How to Think About It
toArray method to fill it. This method copies all elements from the list into the new array.Algorithm
Code
import java.util.ArrayList; import java.util.Arrays; public class ConvertArrayList { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); String[] array = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(array)); } }
Dry Run
Let's trace converting ["apple", "banana", "cherry"] from ArrayList to array.
Create ArrayList
list = ["apple", "banana", "cherry"]
Create new array
new String[3] -> [null, null, null]
Call toArray
array = list.toArray(new String[3]) -> ["apple", "banana", "cherry"]
| Step | Array Contents |
|---|---|
| Before toArray | [null, null, null] |
| After toArray | ["apple", "banana", "cherry"] |
Why This Works
Step 1: Why create a new array?
The toArray method needs an array to fill, so you create one with the same size and type as the ArrayList.
Step 2: How does toArray work?
It copies each element from the ArrayList into the new array in order.
Step 3: Resulting array
The returned array contains all elements from the list and can be used like any normal array.
Alternative Approaches
import java.util.ArrayList; import java.util.Arrays; public class ConvertArrayListAlt { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); Object[] array = list.toArray(); System.out.println(Arrays.toString(array)); } }
import java.util.ArrayList; import java.util.List; public class ConvertArrayListStream { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); String[] array = list.stream().toArray(String[]::new); for (String s : array) { System.out.print(s + " "); } } }
Complexity: O(n) time, O(n) space
Time Complexity
The method copies each element once, so time grows linearly with the number of elements.
Space Complexity
A new array of the same size is created, so space usage is proportional to the list size.
Which Approach is Fastest?
Using toArray(new Type[size]) is efficient and type-safe; streams add overhead but offer flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| toArray(new Type[size]) | O(n) | O(n) | Simple, type-safe conversion |
| toArray() | O(n) | O(n) | Quick but returns Object[] needing casting |
| Streams toArray | O(n) | O(n) | Flexible, functional style |
toArray for type safety.toArray, resulting in an Object array instead of the desired type.