I can sort a list of users without any problems using the following code and Java 8:
CopyOnWriteArrayList<User> allCurrentLoginnedUsersList = new CopyOnWriteArrayList<>();
Collections.sort(allCurrentLoginnedUsersList);
Now, I changed to Java 7 and I saw no errors on eclipse. But now, when running under Java 7 I got this error:
java.lang.UnsupportedOperationException
at java.util.concurrent.CopyOnWriteArrayList$COWIterator.set(CopyOnWriteArrayList.java:1049)
at java.util.Collections.sort(Collections.java:221)
at com.fluent.User.sortAllCurrentLoginnedUsers(User.java:446)
How to fix it?
There was a change between Java 7 (and early version of Java 8) and Java 8u20 in the way Collections.sort
work (issue 8032636, as noted by Holger).
Java 7 Collections.sort(list, c)
specifies that:
This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n² log(n) performance that would result from attempting to sort a linked list in place.
Looking at the code, this is done by obtaining a ListIterator
from the list. However, CopyOnWriteArrayList
listIterator()
method states that the iterator returned does not support the set
operation:
The returned iterator provides a snapshot of the state of the list when the iterator was constructed. No synchronization is needed while traversing the iterator. The iterator does NOT support the
remove
,set
oradd
methods.
This explains the error you are getting when running your code with Java 7. As a workaround, you can refer to this question where the answer is to dump the content of the list into an array, sort the array and put the elements back in the list.
In Java 8, Collections.sort(list, c)
changed implementation:
This implementation defers to the
List.sort(Comparator)
method using the specified list and comparator.
And the new method CopyOnWriteArrayList.sort(c)
(introduced in Java 8) does not use the list iterator so it works correctly.
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