Java ArrayList 与 Arrays.asList() 返回的 List
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25729553/
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
ArrayList vs the List returned by Arrays.asList()
提问by Roam
The method Arrays.asList(<T>...A)
returns a List
representation of A
.
The returned object here is a List
backed by an array, but is not an ArrayList
object.
该方法Arrays.asList(<T>...A)
返回 的List
表示A
。这里返回的对象是一个List
由数组支持的ArrayList
对象,但不是一个对象。
I'm looking for the differences between the object Arrays.asList()
returns and an ArrayList
object-- a quick source to tell these without diving into the code.
我正在寻找对象Arrays.asList()
返回和对象之间的差异 -ArrayList
一个快速来源,无需深入代码即可告诉这些。
TIA.
TIA。
采纳答案by SparkOn
When you call Arrays.asList it does not return a java.util.ArrayList
. It returns a java.util.Arrays$ArrayList
which is a fixed size list backed by the original source array. In other words, it is a view for the array exposed with Java's collection-based APIs.
当您调用 Arrays.asList 时,它不会返回java.util.ArrayList
. 它返回一个java.util.Arrays$ArrayList
由原始源数组支持的固定大小列表。换句话说,它是使用 Java 的基于集合的 API 公开的数组的视图。
String[] sourceArr = {"A", "B", "C"};
List<String> list = Arrays.asList(sourceArr);
System.out.println(list); // [A, B, C]
sourceArr[2] = ""; // changing source array changes the exposed view List
System.out.println(list); //[A, B, ]
list.set(0, "Z"); // Setting an element within the size of the source array
System.out.println(Arrays.toString(sourceArr)); //[Z, B, ]
list.set(3, "Z"); // java.lang.ArrayIndexOutOfBoundsException
System.out.println(Arrays.toString(sourceArr));
list.add("X"); //java.lang.UnsupportedOperationException
list.remove("Z"); //java.lang.UnsupportedOperationException
You cannot add elements to it and you cannot remove elements from it. If you try to add or remove elements from them you will get UnsupportedOperationException
.
您不能向其中添加元素,也不能从中删除元素。如果您尝试在其中添加或删除元素,您将获得UnsupportedOperationException
.
回答by Maroun
I'll expand my comment a little bit.
我会稍微扩展一下我的评论。
One problem that can occur if you use asList
as it wasn't different from ArrayList
object:
如果您使用asList
它,可能会出现一个问题,因为它与ArrayList
对象没有区别:
List<Object> list = Array.asList(array) ;
list.remove(0); // UnsupportedOperationException :(
Here you cannot remove the 0 element because asList
returns a fixed-size list backed by the specified array. So you should do something like:
在这里您不能删除 0 元素,因为asList
返回由指定数组支持的固定大小列表。所以你应该做这样的事情:
List<Object> newList = new ArrayList<>(Arrays.asList(array));
in order to make the newList
modifiable.
为了使newList
可修改。