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
How to add elements in List when used Arrays.asList()
提问by Praful Surve
We cannot perform <Collection>.add
or <Collection>.addAll
operation 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 List
without deleting previous elements in List
?. How can I achieve this?
那么,如果我遇到一个场景,我需要在List
不删除之前的元素的情况下添加新元素List
?我怎样才能做到这一点?
采纳答案by Rohit Jain
Create a new ArrayList
using 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 list
as 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 ArrayList
with 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.
这应该非常有效,因为它可以遍历数组并预先分配目标列表。对于大型阵列,它可能更好也可能不会更好。与往常一样,如果重要,您必须衡量。