java - 为什么在Java中按比较器排序时collections.sort会抛出不受支持的操作异常? [英] Why does collections.sort throw unsupported operation exception while sorting by comparator in Java?
本文介绍了java - 为什么在Java中按比较器排序时collections.sort会抛出不受支持的操作异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我用于按预定义顺序对列表进行排序的代码.itemsSorted 列表中提到了定义的顺序.
Following is my code used to sort a list with predefined order. Defined order is mentioned in itemsSorted list.
final List<String> itemsSorted = myMethod.getSortedItems();
List<String> plainItemList = myMethod2.getAllItems();
final Comparator<String> comparator = new Comparator<String>() {
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)
我不确定为什么该列表不可修改.请帮我解决这个问题.
I'm not sure why the list is unmodifiable. Please help me on this.
推荐答案
该列表不可修改,显然您的客户端方法正在创建一个不可修改的列表(例如使用 Collections#unmodifiableList
等).只需在排序前创建一个可修改的列表:
The list is not modifiable, obviously your client method is creating an unmodifiable list (using e.g. Collections#unmodifiableList
etc.). Simply create a modifiable list before sorting:
List<String> modifiableList = new ArrayList<String>(unmodifiableList);
Collections.sort(modifiableList, comparator);
这篇关于java - 为什么在Java中按比较器排序时collections.sort会抛出不受支持的操作异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文