CopyOnWriteArrayList in Java
The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating a new copy.
The CopyOnWriteArrayList is consists in the java.util. package.
Syntax for declaring a CopyOnWriteArrayList:
public class CopyOnWriteArrayList<T> extends Object implements List, RandomAccess, Cloneable, Serializable
The Following are some specifications regarding the CopyOnWriteArrayList:
- CopyOnWriteArrayList generates a cloned copy of the basic ArrayList. For each update operation the both ArrayList and CopyOnWriteArrayList automatically synchronize at a specific point which is handled by the JVM(Java Virtual Machine). There is no specific effect on them if it is a read operation.
- The CopyOnWriteArrayList is very costly due to creation of the cloned copy for each update operation.
- The ideal use of the CopyOnWriteArrayList is for the read operation.
- The insertion in the CopyOnWriteArrayList accepts the null, duplicates and multiple value objects.
- The remove operation is can not be able to performed by the CopyOnWriteArrayList Iterator. It shows the exception like UnsupportedOperationException.
Constructors used in CopyOnWriteArrayList:
- CopyOnWriteArrayList():
It is a default constructor which is used to create a empty ArrayList.
- CopyOnWriteArrayList(Collection obj):
The CopyOnWriteArrayList(Collection obj) is a parameterized constructor which create and store the elements present in the specified collection.
- CopyOnWriteArrayList(Object [] obj):
TheCopyOnWriteArrayList(Object [] obj) is parameterized constructor which stores the copy of the specified array.
Method Used in CopyOnWriteArrayList:
- add(E e):
The add(E e) inserts the specific element e into the list.
- add(int index, E element):
The add(int Index, E element) inserts the given element e in the list at a particular index.
- addAll(Collection <? Extends E> c):
The addAll(Collection <? Extends E> c) inserts the elements which are included in the particular collection into the end of the list.
- addAll(int index, Collection <? Extends E> c):
The addAll(int index, Collection <? Extends E> c) inserts the elememts which are included in the particular collection into the list at a specific position.
- addAllAbsent(Collection <? Extends E> c):
The addAllAbsent()(Collection <? Extends E> c) inserts the elements from the particular collection if the list does not contain the elements which are included in that collection.
- addIfAbsent(E e):
The addIfAbsent(E e) inserts the element e if that element does not present in the list.
- contains(Object o):
The contains(Object o ) validates if the given element present in the list.
The clone() creates a copy of the list.
- clear():
The clear() removes the each and every element present in the list..
- containsAll(Collection <?> c):
The contains(Collection <?> c) validates if the list contains the elements present in the particular collection.
- equals(Object o):
The equals(Object o) is used for the comparison.
- get(int index):
The get(int index) is to retrieve the element from the with the help of the specified index.
- hashCode():
The hashCode() gives the hashcode value.
- indexOf(Object o):
The element with the first index in the list is returned by the indexOf(Object o) method.
- isEmpty():
If the list is empty, the isEmpty() method returns true.
- remove(Object o):
The remove(Object o) eliminates the initial element from the list.
- remove(Int index):
The remove(int index) eliminates the element from the list with the particular index.
- removeAll(Collection <?> c):
The removeAll(Collection <?> c) removes the all the elements present in the list.
- retainAll(Collection <?> c):
The retainAll(Collection <?> c) retains the elements with the specified collection.
- set(int index, E element):
The set(int index, E element) used to update the element of the list at a particular index.
- size():
the size() return the number of the elements present in the list.
- toArray():
The toArray() returns the array which containing the same elements of the list.
- toString():
The toString() returns the string representation of the List.
Difference between ArrayList and CopyOnWriteArrayList:
They both perform the List interface. However, ArrayList and CopyOnWriteArrayList differ in a number of ways.
- Every update action at a particular point will automatically synchronize both copies of the ArrayList created by CopyOnWriteArrayList, which is handled by the JVM. As a result, threads that are executing read operations are unaffected. As a result, ArrayList lacks thread safety, whereas CopyOnWriteArrayList does.
- If another thread attempts to modify an object while one thread is iterating the run-time error is raised. To overcome this error, the CopyOnWriteArrayList can be used.
- The ArrayList iterator has the ability to remove items while iterating. The CopyOnWriteArrayList Iterator cannot, however, conduct a remove operation while iterating because doing so will cause a run-time exception known as an UnsupportedOperationException.
Example Program:
// Program for the CopyOnWriteArrayList
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Main extends Thread
{
static CopyOnWriteArrayList <String> a = new CopyOnWriteArrayList<String>();
public void run()
{
a.add(“H”);
}
public static void main(String args[])
{
a.add(“A”);
a.add(“B”);
a.add(“C”);
Main c = new Main();
c.run();
Thread.sleep(1000);
Iterator itr = a.iterator();
while(itr.hasNext())
{
String s =(String)itr.next();
System.out.println(s);
Thread.sleep(1000);
}
System.out.println(a);
}
}
Output:
A
B
C
H
[A,B,C,H]
Example Program 2:
// program for remove operation in ArrayList while iterating
import java.util.*;
class Main
{
public static void main(String args [])
{
List a = new ArrayList();
a.add(“A”);
a.add(“B”);
a.add(“C”);
Iterator itr = a.iterator();
while(itr.hasNext())
{
String s =(String)itr.next();
if(s.equals(“B”))
{
itr.remove();
}
}
System.out.println(a);
}
}
Output:
[A, C]
Example Program 3:
// Program for remove operation while iterating in CopyOnWriteArrayLlist.
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
class Copy extends Thread
{
static CopyOnWriteArrayList a = new CopyOnWriteArrayList();
public static void main(String args [])
{
a.add(“A”);
a.add(“B”);
a.add(“C”);
Iterator itr = a.iterator();
while(itr.next())
{
String s =(String)itr.hasNext();
System.out.println(s);
if(s.equals(“B”))
{
itr.remove();
}
}
System.out.println(a);
}
}
Output:
A
B
Exception in thread “main” java.lang.UnsupportedoperationException
Conclusion
The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating a new copy. CopyOnWriteArrayList generates a cloned copy of the basic ArrayList. For each update operation the both ArrayList and CopyOnWriteArrayList automatically synchronize at a specific point which is handled by the JVM(Java Virtual Machine).