What I'm looking for is a generic version of Object[] java.util.Collection.toArray()
or a less verbose alternative to using T[] java.util.Collection.toArray(T[] array)
. I can currently write:
Collection<String> strings;
String[] array = strings.toArray(new String[strings.size()]);
What I'm looking for is something like:
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Collection<T> collection, Class<T> clazz) {
return collection.toArray((T[]) Array.newInstance(clazz, collection.size()));
}
which I can then use as:
String[] array = Util.toArray(strings, String.class);
So is anything like this implemented in Guava or in Commons Collections?
Of course I can write my own (the above), which seems to be as fast as toArray(T[] array).
Iterables.toArray()
from Guava.