为什么在Java中使用comparator进行排序时,collections.sort会抛出不支持的操作异常?
- 论坛
- 为什么在Java中使用comparator进行排序时,collections.sort会抛出不支持的操作异常?
22 浏览
为什么在Java中使用comparator进行排序时,collections.sort会抛出不支持的操作异常?
以下是我用来按预定义顺序对列表进行排序的代码。预定义顺序在itemsSorted列表中提到。
final ListitemsSorted = myMethod.getSortedItems(); List plainItemList = myMethod2.getAllItems(); final Comparator comparator = new Comparator () { public int compare(String str1, String str2) { return orderOf(str1) - orderOf(str2); } private int orderOf(String name) { return ((itemsSorted)).indexOf(name); } }; Collections.sort(plainItemList, comparator); return plainItemList;
以上代码抛出以下异常:
Caused by: java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableList$1.set(Collections.java:1244) at java.util.Collections.sort(Collections.java:221)
我不确定为什么列表是不可修改的。请帮助我解决这个问题。