开发者

Creating a String[] from Guava's Splitter

Is there a more efficient 开发者_如何学运维way to create a string array from Guava's Splitter than the following?

Lists.newArrayList(splitter.split()).toArray(new String[0]);


Probably not so much more efficient, but a lot clearer would be 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.


How about

Iterables.toArray(splitter.split(), String.class);

since there's an Iterables.toArray() method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜