Difference between ArrayList and CopyOnWriteArrayList in Java


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

 ArrayListCopyOnWriteArrayList
SynchronizedArrayList is not synchronized.CopyOnWriteArrayList is synchronized.
Thread SafeArrayList is not thread safe.CopyOnWriteArrayList is thread safe.
Iterator typeArrayList 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 OpearationArrayList iterator supports removal of element during iteration.CopyOnWriteArrayList.remove() method throws exception if elements are tried to be removed during iteration.
PerformanceArrayList is faster.CopyOnWriteArrayList is slower than ArrayList.
Since Java Version1.21.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

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 21-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements