Java 数组到集合:优化的代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4255039/
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-14 15:04:31  来源:igfitidea点击:

Array to Collection: Optimized code

javaarrayscollections

提问by marcolopes

Is there a better way of achieving this?

有没有更好的方法来实现这一目标?

public static List<String> toList(String[] array) {

    List<String> list = new ArrayList(array.length);

    for(int i=0; i<array.length; i++)
        list.add(array[i]);

    return list;
}

NOTE: Arrays.asList(a) Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.). I don't want that behavior.I assume that MY function above bypasses that (or am I wrong?)

注意:Arrays.asList(a) 返回由指定数组支持的固定大小列表。(更改返回的列表“直写”到数组。)。我不想要这种行为。我假设我上面的功能绕过了(或者我错了?)

So, here we have the alternative method:

所以,这里我们有另一种方法:

public static List<String> toList(String[] array) {

    List<String> list = new ArrayList(array.length);

    list.addAll(Arrays.asList(array));

    return list;
}

Just looking at it, I don't believe it's FASTER than the first method.

只是看着它,我不相信它比第一种方法更快

采纳答案by Ralph

What do you mean by better way:

你所说的更好的方法是什么意思:

more readable:

更具可读性:

List<String> list = new ArrayList<String>(Arrays.asList(array));

less memory consumption, and maybe faster (but definitely not thread safe):

更少的内存消耗,也许更快(但绝对不是线程安全的):

public static List<String> toList(String[] array) {
    if (array==null) {
       return new ArrayList(0);
    } else {
       int size = array.length;
       List<String> list = new ArrayList(size);
       for(int i = 0; i < size; i++) {
          list.add(array[i]);
       }
       return list;
    }
}

Btw: here is a bug in your first example:

顺便说一句:这是您的第一个示例中的一个错误:

array.lengthwill raise a null pointer exception if array is null, so the check if (array!=null)must be done first.

array.length如果数组为空,则会引发空指针异常,因此if (array!=null)必须先进行检查。

回答by Jigar Joshi

Arrays.asList(array);    

Example:

例子:

 List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

See Arrays.asListclass documentation.

请参阅Arrays.asList类文档。

回答by Bozho

Arrays.asList(array)

Arraysuses new ArrayList(array). But this is not the java.util.ArrayList. It's very similar though. Note that this constructor takes the array and places it as the backing array of the list. So it is O(1).

Arrays使用new ArrayList(array). 但这不是java.util.ArrayList. 虽然它非常相似。请注意,此构造函数接受数组并将其作为列表的后备数组。所以是这样O(1)

In case you already have the list created, Collections.addAll(list, array), but that's less efficient.

如果您已经创建了列表Collections.addAll(list, array),但效率较低。

Update:Thus your Collections.addAll(list, array)becomes a good option. A wrapper of it is guava's Lists.newArrayList(array).

更新:因此您Collections.addAll(list, array)成为一个不错的选择。它的包装器是番石榴的Lists.newArrayList(array).

回答by posdef

Have you checked Arrays.asList(); see API

你检查过吗Arrays.asList()?见API

回答by ant

What about :

关于什么 :

List myList = new ArrayList(); 
String[] myStringArray = new String[] {"Java", "is", "Cool"}; 

Collections.addAll(myList, myStringArray); 

回答by Mohamed Saligh

You can use:

您可以使用:

list.addAll(Arrays.asList(array));

回答by MarioB.

Yes, there is. You can use the Arrays class from the java.util.* package. Then it's actually just one line of code.

就在这里。您可以使用 java.util.* 包中的 Arrays 类。那么它实际上只是一行代码。

List<String> list = Arrays.asList(array);

回答by npinti

You can try something like this:

你可以尝试这样的事情:

List<String> list = new ArrayList<String>(Arrays.asList(array));

public ArrayList(Collection c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection.

公共数组列表(集合 c)

按照集合的迭代器返回的顺序构造一个包含指定集合元素的列表。ArrayList 实例的初始容量是指定集合大小的 110%。

Taken from here

取自这里

回答by diegoehg

Another way to do it:

另一种方法:

Collections.addAll(collectionInstance,array);

回答by Visruth

Based on the reference of java.util.Collections.addAll(Collection<? super String> c, String... elements)its implementation is similar to your first method, it says

基于java.util.Collections.addAll(Collection<? super String> c, String... elements)其实现的参考 类似于您的第一种方法,它说

Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

将所有指定的元素添加到指定的集合。要添加的元素可以单独指定或作为数组指定。此便捷方法的行为与 c.addAll(Arrays.asList(elements)) 的行为相同,但在大多数实现中,此方法的运行速度可能会明显加快。

Its implementation in jdk is (jdk7)

它在jdk中的实现是(jdk7)

public static <T> boolean addAll(Collection<? super T> c, T... elements) {
    boolean result = false;
    for (T element : elements)
        result |= c.add(element);
    return result;
}

So among your samples the better approach must be Collections.addAll(list, array);

所以在你的样本中,更好的方法必须是 Collections.addAll(list, array);

Since Java 8, we can use Streamapi which may perform better

从 Java 8 开始,我们可以使用Stream性能更好的 api

Eg:-

例如:-

String[] array = {"item1", "item2", "item3"};

Stream<String> stream = Stream.of(array);

//if the array is extremely large 
stream = stream.parallel();

final List<String> list = stream.collect(Collectors.toList());

If the array is very large we can do it as a batch operation in parallel using parallel stream (stream = stream.parallel()) that will utilize all CPUs to finish the task quickly. If the array length is very small parallel stream will take more time than sequential stream.

如果数组非常大,我们可以使用并行流 ( stream = stream.parallel()) 将其作为并行批处理操作来执行,这将利用所有 CPU 快速完成任务。如果数组长度非常小,并行流将比顺序流花费更多的时间。