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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With