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.