UnsupportedOperationException尝试设置二维List

时间:2016-09-19 01:54:09

标签: java list debugging exception

运行以下代码时,我会看到一个Exception,它只是说: Exception in thread "LWJGL Application" java.lang.UnsupportedOperationException

// 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 个答案:

答案 0 :(得分:1)

Collections.nCopies(...)根据文档返回不可变列表。在其中一个列表上调用set(...)会产生UnsupportedOperationException

您可以尝试更改代码,如下所示:

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