Java - How to Convert ArrayList to Array

ArrayList is a resizable List based implementation backed by an array. Sometimes we want to convert an ArrayList object to an array. In this post, we’ll see how to do this in Java.

List interface which the ArrayList extends from requires that classes which implement it provide an implementation of toArray(…) method. If we call the toArray(...) method on an ArrayList object, it returns a new array containing all the elements in the ArrayList. Let’s see how to do this using plain old Java.

1. ArrayList to String[]

Let’s see how to convert an ArrayList of strings to a string array.

package com.codeahoy.ex;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // Add elements to the list
        list.add("List");
        list.add("Set");
        list.add("HashMap");

        // Convert ArrayList to Array
        String[] array = list.toArray(new String[0]);

        // Print the array
        for (String s : array) {
            System.out.println(s);
        }
    }
}

Output:

List
Set
HashMap

The reason we pass new String[0] as an argument to toArray(...) requires some explanation. If we pass an array and the list fits in that array, that is, it has enough space, it is used instead of the library creating a new array. If the size of the ArrayList is greater than the array in the argument, it creates a new array with the same type and returns it instead. So in the example code above, we’re passing an array of size 0 so that it creates and returns a new array object. The newly created array is safe and no references are linked to the ArrayList that created it. We’re free to modify the array. But note that the array is a shallow copy of the elements of the ArrayList.

2. ArrayList to Integer[]

Let’s see how to convert an ArrayList of integers to an integers array.

package com.codeahoy.ex;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();

        // Add elements to the list
        list.add(5);
        list.add(10);
        list.add(15);

        // Convert ArrayList to Array
        Integer[] array = list.toArray(new Integer[0]);

        // Print the array
        for (Integer n : array) {
            System.out.println(n);
        }
    }
}

Output

5
10
15

The following video illustrates the difference between ArrayLists and Arrays, advantages and performance comparison of the two.

Please leave your comments below and like on Facebook or follow on Twitter to stay up-to-date.

comments powered by Disqus