top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Java: What is the difference between ArrayList and CopyOnWriteArrayList?

+3 votes
426 views
Java: What is the difference between ArrayList and CopyOnWriteArrayList?
posted May 29, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Difference:

1) First and foremost difference between CopyOnWriteArrayList and ArrayList in Java is that CopyOnWriteArrayList is a thread-safe collection while ArrayList is not thread-safe and can not be used in multi-threaded environment.

2) Second difference between ArrayList and CopyOnWriteArrayList is that Iterator of ArrayList is fail-fast and throw ConcurrentModificationException once detect any modification in List once iteration begins but Iterator of CopyOnWriteArrayList is fail-safe and doesn't throw ConcurrentModificationException.

3) Third difference between CopyOnWriteArrayList vs ArrayList is that Iterator of former doesn't support remove operation while Iterator of later supports remove() operation.

Here is a complete code Example of CopyOnWriteArrayList which demonstrate that Iterator of CopyOnWriteArrayList doesn't support remove() operation.

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
/**
 *
 * Java program to demonstrate What is CopyOnWriteArrayList in Java,
 * Iterator of CopyOnWriteArrayList
 * doesn’t support add, remove or any modification operation.
 *
 * @author Java67
 */
public class CopyOnWriteArrayListExample{

    public static void main(String args[]) {

        CopyOnWriteArrayList<String> threadSafeList = new CopyOnWriteArrayList<String>();
        threadSafeList.add("Java");
        threadSafeList.add("J2EE");
        threadSafeList.add("Collection");

        //add, remove operator is not supported by CopyOnWriteArrayList iterator
        Iterator<String> failSafeIterator = threadSafeList.iterator();
        while(failSafeIterator.hasNext()){
            System.out.printf("Read from CopyOnWriteArrayList : %s %n", failSafeIterator.next());
            failSafeIterator.remove(); //not supported in CopyOnWriteArrayList in Java
        }
    }
}

Output:

Read from CopyOnWriteArrayList : Java
Read from CopyOnWriteArrayList : J2EE
Read from CopyOnWriteArrayList : Collection
answer Jun 17, 2015 by Karthick.c
...