Java 使用Arrays.asList()时如何在List中添加元素

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

How to add elements in List when used Arrays.asList()

javalist

提问by Praful Surve

We cannot perform <Collection>.addor <Collection>.addAlloperation on collections we have obtained from Arrays.asList.. only remove operation is permitted.

我们不能对从..获得的集合执行<Collection>.add<Collection>.addAll操作Arrays.asList。只允许删除操作。

So What if I come across a scenario where I require to add new Element in Listwithout deleting previous elements in List?. How can I achieve this?

那么,如果我遇到一个场景,我需要在List不删除之前的元素的情况下添加新元素List?我怎样才能做到这一点?

采纳答案by Rohit Jain

Create a new ArrayListusing the constructor:

ArrayList使用构造函数创建一个新的:

List<String> list = new ArrayList<String>(Arrays.asList("a", "b"));

回答by NPE

One way is to construct a new ArrayList:

一种方法是构造一个新的ArrayList

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

Having done that, you can modify listas you please.

完成后,您可以随意修改list

回答by blackpanther

The Constructor for a Collection, such as the ArrayList, in the following example, will take the array as a list and construct a new instance with the elements of that list.

在下面的示例中,集合的构造函数(例如 ArrayList)将数组作为列表,并使用该列表的元素构造一个新实例。

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

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)

回答by Mr.Q

Arrays.asList(),generates a list which is actually backed by an array and it is an array which is morphed as a list. You can use it as a list but you can't do certain operations on it such as adding new elements. So the best option is to pass it to a constructor of another list obj like this:

Arrays.asList(),生成一个实际上由数组支持的列表,它是一个变形为列表的数组。您可以将其用作列表,但不能对其进行某些操作,例如添加新元素。所以最好的选择是将它传递给另一个列表 obj 的构造函数,如下所示:

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

回答by Jens

You can get around the intermediate ArrayListwith Java8 streams:

您可以ArrayList使用 Java8 流绕过中间部分:

    Integer[] array = {1, 2, 3};
    List<Integer> list = Streams.concat(Arrays.stream(array),
                                        Stream.of(4)).collect(Collectors.toList());

This should be pretty efficient as it can just iterate over the array and also pre-allocate the target list. It may or may not be better for large arrays. As always, if it matters you have to measure.

这应该非常有效,因为它可以遍历数组并预先分配目标列表。对于大型阵列,它可能更好也可能不会更好。与往常一样,如果重要,您必须衡量。