Difference between ArrayList and CopyOnWriteArrayList in Java



Following are the notable differences between ArrayList and CopyOnWriteArrayList classes in Java.

  ArrayList CopyOnWriteArrayList
Synchronized ArrayList is not synchronized. CopyOnWriteArrayList is synchronized.
Thread Safe ArrayList is not thread safe. CopyOnWriteArrayList is thread safe.
Iterator type ArrayList iterator is fail-fast and ArrayList throws ConcurrentModificationException if concurrent modification happens during iteration. CopyOnWriteArrayList is fail-safe and it will never throw ConcurrentModificationException during iteration. The reason behind the it that CopyOnWriteArrayList creates a new arraylist every time it is modified.
Remove Opearation ArrayList iterator supports removal of element during iteration. CopyOnWriteArrayList.remove() method throws exception if elements are tried to be removed during iteration.
Performance ArrayList is faster. CopyOnWriteArrayList is slower than ArrayList.
Since Java Version 1.2 1.5

Example

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class Tester {

   public static void main(String args[]) {

      // create an array list
      CopyOnWriteArrayList<String> al = new CopyOnWriteArrayList();
      System.out.println("Initial size of al: " + al.size());

      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");
      al.add(1, "A2");
      System.out.println("Size of al after additions: " + al.size());

      // display the array list
      System.out.println("Contents of al: " + al);

      // Remove elements from the array list
      al.remove("F");
      al.remove(2);
      System.out.println("Size of al after deletions: " + al.size());
      System.out.println("Contents of al: " + al);

      try{
         Iterator<String> iterator = al.iterator();
         while(iterator.hasNext()) {
            iterator.remove();
         }
      }catch(UnsupportedOperationException e) {
         System.out.println("Method not supported:");
      }
      System.out.println("Size of al: " + al.size());
   }
}

This will produce the following result −

Output

Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Method not supported:
Size of al: 5
Updated on: 2020-06-21T12:23:44+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements