Convert an ArrayList to an Array in Java

OK, back on my soap box; this task is somewhat annoying in Java and should be easier.

If you have an ArrayList object and want to convert it to an array of objects, here’s the way to do it with a minimal amount of code.

ArrayList list = new ArrayList();
list.add("abc");
list.add("def");
list.add("ghi");
 
Object[] array = list.toArray();
 
for (Object x : array)
    System.out.println(x);

However, a limitation of this approach is that the array you get will be a bunch if Object objects, and you may want them as something else like Strings. If you wanted to get an array of Strings, you would have to do something like this:

String[] array = (String[])list.toArray(new String[0]);

Let’s be honest…it’s ugly and feels like a hack.

For that reason, I have a class with a method that implements this code for me so I only had to do it once.

public static String[] ConvertToStringArray(ArrayList list)
{
    return (String[])list.toArray(new String[0]);
}

The bummer with this is that you would have to create a separate method for each class for which you want to be able to do this (e.g. Integer, Double, custom class). I don’t know of any elegant way around this. But at least you know that you only have to create those methods one time, and it’s a simple matter of copy/paste.

Leave a Reply