2016-09-19 74 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))); 
} 
相关问题