以下是我的清单定义。
static List<Integer> list = Arrays.asList(112, 323, 368, 369, 378);
该列表的固定大小为5.
在调用像这样的添加
list.add(200);
这不应该是编译时错误吗?相反,它抛出异常 在运行时
java.lang.UnsupportedOperationException
答案 0 :(得分:4)
我们知道Arrays.asList
会返回List
固定大小的array
,并由Stateful
固定长度支持。
现在编译器在编译时并不知道数组的长度。除非你运行程序,否则你不知道运行时的长度。
简而言之,您无法在编译时修改数组:)
答案 1 :(得分:3)
来自Java DOCs
Returns a **fixed-size** list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
Parameters:
a - the array by which the list will be backed
Returns:
a list view of the specified array
由于这是固定大小,因此您无法修改此列表中的添加元素。
答案 2 :(得分:2)
您从Arrays.asList收到的此List实现是阵列上的一个特殊视图 - 您无法更改它的大小。