Pregunta

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).

¿Fue útil?

Solución

Iterables.toArray() from Guava.

Otros consejos

You can shorten it with

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

which also happens to be more efficient.

With Java 8 you can also use this, but it seems unnecessarily complicated and is probably slower:

String[] array = strings.stream().toArray(String[]::new);     // Java 8
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top