In this post, you will learn how to convert ArrayList to array in Java using two methods:
- With a for loop
- Using toArray() method
Convert ArrayList to Array in Java with a for loop
In this example, we create an empty array, then iterate over the list and add each element to the array.
class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("item1"); list.add("item2"); list.add("item3"); list.add("item4"); // create an empty array with length == size of the list String[] array = new String[list.size()]; // iterate over a list and add each element to the array for (int i = 0; i < list.size(); i++) { array[i] = list.get(i); } // print array elements System.out.println(Arrays.toString(array)); } }
Output: [item1, item2, item3, item4]
Convert list to array using toArray() method
Instead of copying each element of the list manually to the array, like in the above example, we can use the toArray() method that converts the list to an array.
Example
class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("item1"); list.add("item2"); list.add("item3"); list.add("item4"); // convert ArrayList to array String[] array = list.toArray(new String[list.size()]); // print array elements System.out.println(Arrays.toString(array)); } }
Output: [item1, item2, item3, item4]
And that’s it! If you want to learn how to convert an array to a list, check out this post.
Happy coding!