Java Guava 或 Apache Commons Collections 中是否有 toArray() 的通用版本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21729668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:22:49  来源:igfitidea点击:

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

javaguavaapache-commons

提问by Mihai

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:

我正在寻找的是Object[] java.util.Collection.toArray()使用T[] java.util.Collection.toArray(T[] array). 我目前可以写:

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?

那么这样的东西是在 Guava 还是 Commons Collections 中实现的呢?

Of course I can write my own (the above), which seems to be as fast as toArray(T[] array).

当然我可以自己写(上面的),好像和toArray(T[] array)一样快。

采纳答案by axtavt

Iterables.toArray()from Guava.

Iterables.toArray()来自番石榴。

回答by assylias

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:

在 Java 8 中,您也可以使用它,但它似乎不必要地复杂并且可能更慢:

String[] array = strings.stream().toArray(String[]::new);     // Java 8