2016-09-19 68 views
0

當運行下面的代碼,我帶有一個異常簡單地說,價值: Exception in thread "LWJGL Application" java.lang.UnsupportedOperationExceptionUnsupportedOperationException異常試圖設置二維表

// Declare the main List for this situation 
List<List<Integer>> grid = new ArrayList<List<Integer>>(); 

// Initialize each value as 0, making a list of 0s, the length equal to COLUMNS, in a list of Lists, where the length of that is ROWS 
// ROWS and COLUMNS have been defined as constants beforehand. Right now they are both equal to 8 
for (int row = 0; row < ROWS; row++) { 
    grid.add(Collections.nCopies(COLUMNS, 0)); 
} 

// Now set the first element of the first sub-List 
grid.get(0).set(0, Integer.valueOf(2)); 

什麼實際上,我試圖做的是設置元素在計劃中的其他位置計算的特定值。在調查了這個問題之後,我將其縮小到這些行,並發現任何值都會嘗試更改元素以引發異常。我已經嘗試了在其他地方計算的實際值,即數字文字2,現在樣本中有什麼。我所嘗試的一切都會拋出UnsupportedOperationException。我該怎麼辦?

回答

1

Collections.nCopies(...)根據文檔返回不可變列表。在其中一個列表上調用set(...)將導致UnsupportedOperationException

你可以嘗試更改代碼如下:

for (int row = 0; row < ROWS; row++) { 
    grid.add(new ArrayList<>(Collections.nCopies(COLUMNS, 0))); 
} 
相關問題