UnsupportedOperationException while iterating over CopyOnWriteArrayList

2.2k Views Asked by At

I came across the following statement in a book:

Any mutating methods called on a copy-on-write-based Iterator or ListIterator (such as add, set or remove) will throw an UnsupportedOperationException.

But when I run the following code, it works just fine and doesn't throw the UnsupportedOperationException.

List<Integer> list = new CopyOnWriteArrayList<>(Arrays.asList(4, 3, 52));
System.out.println("Before " + list);
for (Integer item : list) {
    System.out.println(item + " ");
    list.remove(item);
}
System.out.println("After " + list);

The code above gives the following result:

Before [4, 3, 52]
4 
3 
52 
After []

Why am I not getting the exception while I am modifying the given list using the remove method?

2

There are 2 best solutions below

0
On BEST ANSWER

You're calling remove on the list itself, which is fine. The documentation states that calling remove on the list's iterator would throw an UpsupportedOperationException. E.g.:

Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
    Integer item = iter.next(); 
    System.out.println(item + " ");
    iter.remove(); // Will throw an UnsupportedOperationException
}
0
On

It looks good with Mureinik's answer. However, if you deep dive into this -

If using ArrayList

  • Use for loop and list remove(current_index) method, it works fine.

And with iterator approach -

  • Use iterator remove() method instead of list remove(), it works fine
  • Throws ConcurrentModificationException if use list remove() method

If in multi-threaded environment -

Use CopyOnWriteArrayList

  • With list remove(current_element) it works fine
  • With Iterator or ListIterator remove() method, it throws UnsupportedOperationException

Take a look at below example -

import java.util.*;
import java.util.concurrent.*;
public class AvoidCMEExample {
   public static void main(String args[]) {
        List<String> listOfBooks = new ArrayList<>();  
       listOfBooks.add("Programming Pearls");
       listOfBooks.add("Clean Code");
       listOfBooks.add("Effective Java");
       listOfBooks.add("Code Complete");
       System.out.println("List before : " + listOfBooks);
       /*for(int i=0; i<listOfBooks.size(); i++){
           String book = listOfBooks.get(i);
           if(book.contains("Programming")){
               System.out.println("Removing " + book);
               listOfBooks.remove(i); // works fine
           }
       }*/
       Iterator<String> itr = listOfBooks.iterator();
       while(itr.hasNext()){
            String book = itr.next();
            if(book.contains("Programming")){
               System.out.println("Removing " + book);
               //listOfBooks.remove(book); // will throw CME
               itr.remove(); // using iterator remove(), it works fine
           }
       }
       System.out.println("List after : " + listOfBooks);
       
       List<String> list = new CopyOnWriteArrayList<>(); 
       list.add("B"); list.add("W"); list.add("Q"); list.add("S");
       System.out.println("\n\nList before : " + list);
       Iterator<String> itr1 = list.iterator();
       while(itr1.hasNext()){
            String book = itr1.next();
            if(book.contains("Q")){
               System.out.println("Removing " + book);
               list.remove(book); // works fine on list object remove()
               itr1.remove(); // throws UnsupportedOperationException on iterator, ListIterator obj
           }
       }
       System.out.println("List after : " + list);       
   }
}