27 March 2010

Converting a list into an array

Valid since: op4j 1.0

Description
Convert a list of objects (List<T>) into an array of the same type (T[]).

Scenario
We have a List<String> variable called elementList, containing:
// elementList == LIST [ "earth", "air", "fire", "water" ]
...and we want to convert this variable into a String[] object.

Recipe
Execute the toArrayOf(Type) action on the list:

String[] elementArray =
    Op.on(elementList).toArrayOf(Types.STRING).get();


Comments
In the example above, it was necessary to specify the type of the array elements (String) with a javaRuntype Type because Java does not create arrays by instantiating a generic class like java.util.List or java.util.Set, but rather by creating an instance of a specific String[] class. This is why op4j needs the class to be used for creating the new array in the form of an org.javaruntype.type.Type object.

This would not be needed, for example, if we wanted to create a set:
Set<String> elementSet =
    Op.on(elementsList).toSet().get();

Let's look at the equivalent non-op4j Java code for the List-to-Array conversion:
String[] elementArray = 
    elementList.toArray(new String[elementList.size()]);

No comments:

Post a Comment