Arrays.asList() 有疑问? [英] Arrays.asList() doubt?
问题描述
人们说asList
方法将数组转换为列表而不是复制,因此'aList' 中的每个更改都会反映到'a' 中.因此,在 'aList' 中添加新值是非法的,因为数组具有固定大小.
People say that asList
method convert the array into list and its not copying, so every change in 'aList' will reflect into 'a'. So add new values in 'aList' is illegal, since array have fixed size.
但是,asList()
方法返回 ArrayList
.编译器如何区分第 3 行和第 5 行.第 3 行给出了异常 (UnsupportedOperationException
).
But, asList()
method returns ArrayList<T>
. How the compiler differentiates line 3 from 5. Line 3 gives me exception (UnsupportedOperationException
).
String[] a = {"a","b","c","d"};//1
List<String> aList = Arrays.asList(a);//2
aList.add("e");//3
List<String> b = new ArrayList<String>();//4
b.add("a");//5
推荐答案
你从 Arrays.asList
收到的这个 List 实现是数组的一个特殊视图——你不能改变它的大小.
This List implementation you receive from Arrays.asList
is a special view on the array - you can't change it's size.
Arrays.asList()
的返回类型是 java.util.Arrays.ArrayList
经常与 java.util.ArrayList
混淆>.Arrays.ArrayList
只是将数组显示为一个列表.
The return type of Arrays.asList()
is java.util.Arrays.ArrayList
which is often confused with java.util.ArrayList
. Arrays.ArrayList
simply shows the array as a list.
这篇关于Arrays.asList() 有疑问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!