Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 962
Poppy Avatar asked Feb 18 '14 12:02

Poppy


People also ask

How do you handle unsupported operation exception in Java?

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList , which can be modified. An unmodifiable collection or data structure should not be attempted to be modified.

Does collections sort use comparator?

While using the Comparable interface, we do not need to make any changes to the code. This is because the sort functions of the collections class automatically use the compareTo method in the class. However, while we implement the Comparator interface, we need to use the comparator name along with the sort function.

What is unsupported operation exception in Java?

An UnsupportedOperationException is a subclass of RuntimException in Java and it can be thrown to indicate that the requested operation is not supported. The UnsupportedOperationException class is a member of the Java Collections Framework.

How does sort work with comparator?

Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else. Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator.


1 Answers

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); 
like image 141
qqilihq Avatar answered Sep 20 '22 13:09

qqilihq