JavaDevNotes.com

Java ArrayList To Array

We will show in this post on how to convert an ArrayList to a Array in Java. Although ArrayList are usually more flexible and powerful, sometimes we need to convert it to simple arrays. Most common use case is passing as parameter to a third party API, that we have no liberty of modifying. Check the samples below.

Convert ArrayList to Array Using toArray()

One of the simplest way is just to invoke the toList() method of an ArrayList. Here is the syntax:
Object[] toArray()
It has no parameters and the result an Object Array. This method creates a new array that contains all the elements of the List. Here is a simple example:
package test;
import java.util.ArrayList;
/**
 * A simple ArrayList to Array Example:
 */
public class TestExample {
    public static void main(String[] args) {
        ArrayList<String> myList = new ArrayList<String>();
        myList.add("Bike");
        myList.add("Bus");
        myList.add("Car");
        Object[] myArray = myList.toArray();
        for (Object myObject : myArray) {
           System.out.println(myObject);
        }
    }
}
As shown, the toArray() returns an array of objects. Below is the expected output:
Bike
Bus
Car
Note that the return type is strictly object array and not string array. Hence this code will result in an Exception.
package test;
import java.util.ArrayList;
/**
 * A simple ArrayList to Array Example:
 */
public class TestExample {
    public static void main(String[] args) {
        ArrayList<String> myList = new ArrayList<String>();
        myList.add("Boke");
        myList.add("Bus");
        myList.add("Car");
        String[] myArray = (String[]) myList.toArray();
    }
}

The Exception stacktrace will print:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
	at test.TestExample.main(TestExample.java:12)

Here is another example of using toArray but applied on Integer objects.
package test;
import java.util.ArrayList;
/**
 * A simple ArrayList to Array Example:
 */
public class TestExample {
    public static void main(String[] args) {
        ArrayList<Integer> myList = new ArrayList<Integer>();
        myList.add(Integer.valueOf(5));
        myList.add(Integer.valueOf(7));
        myList.add(Integer.valueOf(9));
        Object[] myArray = myList.toArray();
        for (Object myObject : myArray) {
           System.out.println(myObject);
        }
    }
}

Convert ArrayList to Array Using toArray(T[] a)

If we don't want an Object array returned, but of a specific type, we may use the following syntax:

<T> T[] toArray(T[] a)

The JavaDoc says that the parameter is "the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.". Here is an example code:
package test;
import java.util.ArrayList;
/**
 * A simple ArrayList to Array Example:
 */
public class TestExample {
    public static void main(String[] args) {
        ArrayList<Integer> myList = new ArrayList<Integer>();
        myList.add(Integer.valueOf(5));
        myList.add(Integer.valueOf(7));
        myList.add(Integer.valueOf(15));
        Integer[] myArray = myList.toArray(new Integer[0]);
        for (Integer myInt: myArray) {
           System.out.println(myInt);
        }
    }
}
And the code will run without problems or Exceptions. However, if we mix the types, we may get Exception. For example:
package test;
import java.util.ArrayList;
/**
 * A simple ArrayList to Array Example:
 */
public class TestExample {
    public static void main(String[] args) {
        ArrayList<Integer> myList = new ArrayList<Integer>();
        myList.add(Integer.valueOf(5));
        myList.add(Integer.valueOf(7));
        myList.add(Integer.valueOf(15));
        String[] myArray = myList.toArray(new String[0]);
        for (String myStr: myArray) {
           System.out.println(myStr);
        }
    }
}

This code will raise the following Exception because we can't convert ArrayList of Integer to String array:

Exception in thread "main" java.lang.ArrayStoreException
	at java.lang.System.arraycopy(Native Method)
	at java.util.Arrays.copyOf(Unknown Source)
	at java.util.ArrayList.toArray(Unknown Source)
	at test.TestExample.main(TestExample.java:12)

Custom Code

We can always fallback to writing our own solution, so we are guaranteed of behavior:
package test;
import java.util.ArrayList;
/**
 * A simple ArrayList to Array Example:
 */
public class TestExample {
    public static void main(String[] args) {
        ArrayList<Integer> myList = new ArrayList<Integer>();
        myList.add(Integer.valueOf(100));
        myList.add(Integer.valueOf(200));
        myList.add(Integer.valueOf(300));
        Integer[] myArray = new Integer[myList.size()];
        for (int i = 0; i < myList.size(); i++) {
           myArray[i] = myList.get(i);
        }
        for (Integer myInt : myArray) {
           System.out.println(myInt);
        }
    }
}

Convert ArrayList to Array Using Streams in Java 8

Java 8's stream offers very cool ways of transforming objects. Below is an example of how to convert an ArrayList to Array in Java 8 using streams:

package test;
import java.util.ArrayList;
/**
 * A simple ArrayList to Array Example:
 */
public class TestExample {
    public static void main(String[] args) {
        ArrayList<Integer> myList = new ArrayList<Integer>();
        myList.add(Integer.valueOf(5));
        myList.add(Integer.valueOf(7));
        myList.add(Integer.valueOf(15));
        Integer[] myArray = myList.stream().toArray(Integer[]::new);
        for (Integer myInt : myArray) {
           System.out.println(myInt);
        }
    }
}