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< T>
。编译器如何区分第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
$ b b
推荐答案
从 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屋!