在Java中,如果创建了一个不可修改的列表,即使用Collections.unmodifiableList()方法封装了一个列表,那么就不能向其中添加或删除元素,否则就会出现“Unsupported operation: Cannot add to an unmodifiable list”异常。解决方法是在创建列表时,将需要添加的元素全部添加进去,然后再使用Collections.unmodifiableList()方法进行封装,以确保不会对列表做出任何更改。示例代码如下:
List
// 尝试向不可修改的列表中添加元素 try { unmodifiableList.add("orange"); } catch (UnsupportedOperationException e) { System.out.println("Unsupported operation: " + e.getMessage()); }
// 尝试修改不可修改的列表 try { mutableList.set(0, "pear"); System.out.println(unmodifiableList); } catch (UnsupportedOperationException e) { System.out.println("Unsupported operation: " + e.getMessage()); }
输出如下:
[apple, banana] Unsupported operation: Cannot add to an unmodifiable list Unsupported operation: Cannot modify an unmodifiable list