Is there any generic version of toArray() in Guava or Apache Commons Collections?

StackOverflow https://stackoverflow.com/questions/21729668

  •  10-10-2022
  •  | 
  •  

سؤال

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.

نصائح أخرى

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top