问题
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