Zodiac Zubeda Zodiac Zubeda - 4 months ago 18
Java Question

UnsupportedOperationException trying to set value of two dimensional List

When running the following code, I am presented with an Exception that simply says:

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));

What I'm actually trying to do is set the element to a specific value that is calculated somewhere else in the program. After investigating the problem I'm narrowed down to these lines, and have found that any value I try to change the element to throws the Exception. I have tried the actual value calculated elsewhere that is to be there, the numeric literal 2, and now what is there in the sample. Everything I try throws the UnsupportedOperationException. What should I do?


Collections.nCopies(...) returns an immutable list per the documentation. Calling set(...) on one of these lists will result in an UnsupportedOperationException.

You could try changing the code as follows:

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