Java 为什么在为固定大小的列表调用add时出现运行时异常?

Java 为什么在为固定大小的列表调用add时出现运行时异常?,java,Java,下面是我的列表定义 static List<Integer> list = Arrays.asList(112, 323, 368, 369, 378); 这不应该是编译时错误吗?相反,它抛出了一个例外 运行时 java.lang.UnsupportedOperationException 您从阵列接收的此列表实现。asList是阵列上的一个特殊视图-您无法更改其大小。我们知道阵列。asList返回固定长度的阵列支持的固定大小的列表 现在编译器在编译时不知道数组的长度。除非运行程

下面是我的列表定义

static List<Integer> list = Arrays.asList(112, 323, 368, 369, 378);
这不应该是编译时错误吗?相反,它抛出了一个例外 运行时

java.lang.UnsupportedOperationException

您从阵列接收的此列表实现。asList是阵列上的一个特殊视图-您无法更改其大小。

我们知道
阵列。asList
返回固定长度的
阵列支持的固定大小的
列表

现在编译器在编译时不知道数组的长度。除非运行程序,否则在运行时不知道长度

简而言之,您不能在编译时修改数组:)

来自Java文档

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
返回指定数组支持的**固定大小**列表。(更改返回的列表“直写”到数组。)此方法与collection.toArray()结合使用,充当基于数组和基于集合的API之间的桥梁。返回的列表可序列化并实现随机访问。
此方法还提供了一种方便的方法,可以创建初始化为包含多个元素的固定大小列表:
List stooges=Arrays.asList(“Larry”、“Moe”、“Curly”);
参数:
a-用于备份列表的数组
返回:
指定数组的列表视图

因为这是固定的大小,所以您不能修改此列表中的添加元素。

同意,例如,给定代码5的列表大小。我知道尺寸不能改变。我的问题是为什么运行时而非编译时异常?我希望了解thisOP知道它不受支持。问题是,为什么编译器不知道它不受支持。问题是,
为什么编译器不知道
调用asList()本身可能会建议不允许添加/删除。所以编译器可以抛出异常。不是吗?而且编译器也不知道数组是“固定大小”的。这是一个只有类知道的实现细节。@AbhishekSaxena编译器无法神奇地猜测(您将向其中添加一些内容)并抛出异常。当你尝试/做不正常的事情时,它会抛出异常。。
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