Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Collections.sort(List) work in Java 8 with CopyOnWriteArrayList but not in Java 7?

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?

like image 386
Tum Avatar asked Jan 16 '16 13:01

Tum


1 Answers

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 or add 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.

like image 193
Tunaki Avatar answered Oct 12 '22 10:10

Tunaki