ArrayList 与 Arrays.asList() 返回的 List [英] ArrayList vs the List returned by Arrays.asList()
问题描述
方法Arrays.asList(
返回一个 List
表示 A
.这里返回的对象是一个 List
由数组支持,但不是 ArrayList
对象.
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()
返回和一个 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.
TIA.
推荐答案
当您调用 Arrays.asList 时,它不会返回 java.util.ArrayList
.它返回一个 java.util.Arrays$ArrayList
,它是一个由原始源数组支持的固定大小的列表.换句话说,它是使用 Java 的基于集合的 API 公开的数组的视图.
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.
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
您不能向其中添加元素,也不能从中删除元素.如果您尝试向其中添加或删除元素,您将收到 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
.
这篇关于ArrayList 与 Arrays.asList() 返回的 List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!