Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort CopyOnWriteArrayList

I want to sort CopyOnWriteArrayList. But when I tried to run the following code

It is throwing unsorted operation exception.

public class CopyOnWriteArrayListExample {

  public static void main(final String[] args) {
     List<String> list = new CopyOnWriteArrayList<>();
    list.add("3");
    list.add("2");
    list.add("1");

    Collections.sort(list);
   }
}

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.concurrent.CopyOnWriteArrayList$COWIterator.set(CopyOnWriteArrayList.java:1049)
at java.util.Collections.sort(Collections.java:159)
at com.sac.list.CopyOnWriteArrayListExample.main(CopyOnWriteArrayListExample.java:15)  

Thanks in advance.

like image 817
Sachin Sachdeva Avatar asked Mar 02 '15 08:03

Sachin Sachdeva


People also ask

How do I get rid of CopyOnWriteArrayList?

The remove(int index) method of CopyOnArrayList in Java is used to remove the element at the specified position in the list. Parameters: This method accepts a mandatory parameter index which specifies the position of the element. Return Type: This method returns the list after deleting the specified element.

What is the best use of CopyOnWriteArrayList?

CopyOnWriteArrayList is a thread-safe variant of ArrayList where operations which can change the ArrayList (add, update, set methods) creates a clone of the underlying array. CopyOnWriteArrayList is to be used in a Thread based environment where read operations are very frequent and update operations are rare.

Is CopyOnWriteArrayList concurrent?

CopyOnWriteArrayList is a concurrent Collection class introduced in Java 5 Concurrency API along with its popular cousin ConcurrentHashMap in Java.


1 Answers

Collections.sort uses ListIterator.set

    ...
    for (int j=0; j<a.length; j++) {
        i.next();
        i.set((T)a[j]);
    }

but CopyOnWriteArrayList's ListIterator does not support the remove, set or add methods.

Workaround:

    Object[] a = list.toArray();
    Arrays.sort(a);
    for (int i = 0; i < a.length; i++) {
        list.set(i, (String) a[i]);
    }
like image 191
Evgeniy Dorofeev Avatar answered Oct 04 '22 04:10

Evgeniy Dorofeev