Monday, November 22, 2010

Converting Java List (or any Java collection) to Array

There are many times when you need to create dynamic data structure that hold data and then convert it into array.

Collection interface posses method T[] toArray(T[] a). We can use this method to convert our list or other collection into array.

By default toArray method provide service of returning of Object array (Object[]). If this is not what we want and we knows type of the array, then we can provide our type and avoid explicit converting.

To do that, we need to provide array type and instance of that array type like so:

List list = new ArrayList();
String[] stringList = (String[])list.toArray(new String[list.size()]);

Please see details in Java API

No comments:

Post a Comment