java 从 Guava 的 Splitter 创建一个 String[]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7602943/
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
Creating a String[] from Guava's Splitter
提问by slipheed
Is there a more efficient way to create a string array from Guava's Splitterthan the following?
有没有比以下更有效的方法来从Guava 的 Splitter创建字符串数组?
Lists.newArrayList(splitter.split()).toArray(new String[0]);
回答by Philipp Reichart
Probably not so much more efficient, but a lot clearer would be Iterables.toArray(Iterable, Class)
可能效率没有那么高,但会更清晰 Iterables.toArray(Iterable, Class)
This pretty much does what you do already:
这几乎可以完成您已经在做的事情:
public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
Collection<? extends T> collection = toCollection(iterable);
T[] array = ObjectArrays.newArray(type, collection.size());
return collection.toArray(array);
}
By using the collection.size()
this should even be a tick faster than creating a zero-length array just for the type information and having toArray()
create a correctly sized array from that.
通过使用collection.size()
this 甚至应该比仅为类型信息创建零长度数组并toArray()
从中创建正确大小的数组快一点。
回答by Jason S
How about
怎么样
Iterables.toArray(splitter.split(), String.class);
since there's an Iterables.toArray()
method
因为有Iterables.toArray()
方法