以下是我的清單定義。爲什麼運行時調用添加固定大小列表異常?
static List<Integer> list = Arrays.asList(112, 323, 368, 369, 378);
名單有固定的尺寸爲5
在調用這樣
list.add(200);
添加不應該這個是編譯時錯誤?相反,它拋出異常 下方在運行時
java.lang.UnsupportedOperationException
以下是我的清單定義。爲什麼運行時調用添加固定大小列表異常?
static List<Integer> list = Arrays.asList(112, 323, 368, 369, 378);
名單有固定的尺寸爲5
在調用這樣
list.add(200);
添加不應該這個是編譯時錯誤?相反,它拋出異常 下方在運行時
java.lang.UnsupportedOperationException
我們知道Arrays.asList
返回一個固定長度的List
,它由固定長度的array
支持。編程時編譯器不知道數組的長度。除非你運行這個程序,否則你不知道運行時的長度。
總之,你不能修改數組在編譯時 :)
這個你從Arrays.asList收到清單的實施是陣列上的一個特殊視圖 - 你不能改變它的大小。
對於給定的代碼5同意的是列表大小。我知道尺寸不能改變。我的問題是爲什麼運行時和不編譯時間異常?我想了解這個 –
OP知道它不被支持。問題是,爲什麼編譯器不知道 –
希望@suresh已經回答了你的問題。 – Shriram
從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
由於這是固定的大小,所以你不能修改元素加入到這個名單。
OP知道它不被支持。問題是,'編譯器爲什麼不知道' –
調用asList()本身可以建議添加/刪除不允許。所以編譯器可以拋出異常。不是嗎? –
而編譯器也不知道該數組是「固定大小」。這是僅供班級所知的實施細節。 – Codebender
@AbhishekSaxena編譯器不能神奇地猜測(你將添加幾件事)並拋出異常。當你嘗試/做出異常的事情時,它確實會拋出異常。 –