Computer >> Computer tutorials >  >> Programming >> Java

Difference between ArrayList and CopyOnWriteArrayList in Java programming.


Both ArrayList and CopyOnWriteArrayList are the implementation of the List interface in Java. But there are certain differences as well.

The following are the important differences between ArrayList and CopyOnWriteArrayList.

Sr. No.KeyArrayListCopyOnWriteArrayList
1SynchronizationArrayList is not synchronized in nature.CopyOnWriteArrayList on other hand is synchronized in nature i.e at a time only one thread can access the object.
2PerformanceArrayList is fast as no synchronization in its operation.Synchronization makes CopyOnWriteArrayList slow in performance.
3Fail safetyArrayList iterators are failed fast and throw ConcurrentModificationException on modification during the traverse.CopyOnWriteArrayList are fail-safe and allow modification during the traverse.
4Remove elementAn iterator of ArrayList can perform remove operation while iteration.CopyOnWriteArrayList cant performs remove operation while iteration, otherwise it will throw run-time exception UnsupportedOperationException.
5Introduction in JavaArrayList is older than CopyOnWriteArrayList as it was added in java version 1.2.CopyOnWriteArrayList class was added in java version 1.5 (or java 5).
6PackageArrayList class is present in java.util package.CopyOnWriteArrayList class is present in java.util.concurrent package.

Example of ArrayList vs CopyOnWriteArrayList

ArrayListDemo.java

import java.util.*;
public class ArrayListDemo{
   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")){
            itr.remove();
         }
      }
      System.out.println(l);
   }
}

Output

[A,C]

Example

CopyOnWriteArrayListDemo.java

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
class CopyOnWriteArrayListDemo 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