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

孤人 提交于 2021-02-05 20:54:14

问题


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;

The above code throws

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.


回答1:


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


来源:https://stackoverflow.com/questions/21854353/why-does-collections-sort-throw-unsupported-operation-exception-while-sorting-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!