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.
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.
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.
CopyOnWriteArrayList is a concurrent Collection class introduced in Java 5 Concurrency API along with its popular cousin ConcurrentHashMap in Java.
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]);
}
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