Open In App

Difference between ArrayList and CopyOnWriteArrayList

Both ArrayList and CopyOnWriteArray implement List interface. But There are lots of differences between ArrayList and CopyOnWriteArrayList:




// Java program to illustrate ArrayList
import java.util.*;
  
class CopyDemo
{
    public static void main(String[] args) 
    {
        ArrayList l = new ArrayList();
        l.add("A");
        l.add("B");
        l.add("C");
        Iterator itr = l.iterator();
          
        while (itr.hasNext()) 
        {
            String s = (String)itr.next();
              
            if (s.equals("B"))
            {
                // Can remove
                itr.remove();
            }
        }
        System.out.println(l);
    }
}

Output:

[A,C]




// Java program to illustrate CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
  
class CopyDemo extends Thread {
      
    static CopyOnWriteArrayList l = new CopyOnWriteArrayList();
      
    public static void main(String[] args) 
                throws InterruptedException
    {
        l.add("A");
        l.add("B");
        l.add("C");
        Iterator itr = l.iterator();
          
        while (itr.hasNext())
        {
            String s = (String)itr.next();
            System.out.println(s);
              
            if (s.equals("B"))
            {
                // Throws RuntimeException
                itr.remove();
            }
            Thread.sleep(1000);
        }
        System.out.println(l);
    }
}

Output:

A
B
Exception in thread "main" java.lang.UnsupportedOperationException

Article Tags :