java - 为什么在Java中按比较器排序时collections.sort会抛出不受支持的操作异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21854353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:04:24  来源:igfitidea点击:

Why does collections.sort throw unsupported operation exception while sorting by comparator in Java?

javasortingcollectionsarraylist

提问by Poppy

Following is my code used to sort a list with predefined order. Defined order is mentioned in itemsSorted list.

以下是我用于按预定义顺序对列表进行排序的代码。itemsSorted 列表中提到了定义的顺序。

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;

The above code throws

上面的代码抛出

Caused by: java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableList.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.

我不确定为什么该列表不可修改。请帮我解决这个问题。

采纳答案by qqilihq

The list is not modifiable, obviously your client method is creating an unmodifiable list (using e.g. Collections#unmodifiableListetc.). Simply create a modifiable list before sorting:

该列表不可修改,显然您的客户端方法正在创建一个不可修改的列表(使用例如Collections#unmodifiableList等)。只需在排序前创建一个可修改的列表:

List<String> modifiableList = new ArrayList<String>(unmodifiableList);
Collections.sort(modifiableList, comparator);