I want to sort CopyOnWriteArrayList. But when I tried to run the following code
It is throwing unsorted operation exception.
Evgeniy's solution points in the right way, but list.set(i, (String) a[i]) has to gain the lock on list for each element in the list. If there is a concurrent thread which writes into list this will slow down the loop dramatically.
To minimize blocking it's better to reduce the number of statements which alter list:
CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();
// ... fill list with values ...
ArrayList temp = new ArrayList<>();
temp.addAll(list);
Collections.sort(temp);
list.clear(); // 1st time list is locked
list.addAll(temp); // 2nd time list is locked
The downside is that if a concurrent thread reads list between clear() and addAll(temp) it will see an empty list wheras with Evgeniy's solution it may see a partially sorted list.