In Java, CopyOnWriteArrayList class was introduced in JDK 1.5. This class implements the List interface. It is a modified version of ArrayList. it is very costly because each time when updating is performed a cloned copy is created. It is threaded safe. In this class remove operation can not be performed, if performed UnsupportedOperationException error will occur.
S.no. | Method | Description |
---|---|---|
1 | add(E e) | It is used to add an element to the end of the list. |
2 | add(int index, E element) | It is used to add an element at the specified position of the list. |
3 | add(int index, Collection c) | It is used to add an element at the specified collection at the specified position of the list. |
4 | clear() | It is used to remove all the elements from the list. |
5 | equals(Object o) | It is used to compare an element from another element in the list. |
6 | get(int index) | It is used to get the element from the specified position in the list. |
7 | hashCode() | It is used to get hash code from the list. |
8 | indexOf(Object o) | It is used to get the first element from the list. If the list is empty then it returns -1. |
9 | Iterator() | It returns all the elements from the list. Using Iterator. |
10 | lastIndexOf(Object o) | It is used to get the Last element from the list. If the list is empty then it returns -1. |
11 | listIterator() | It is used to get the Iterated list in a proper sequence. |
12 | remove(int index) | It is used to remove the specified element from the list. |
13 | removeRange(intfromIndex, inttoIndex) | It is used to remove an element from the specified range. |
14 | set(int index, E element) | It is used to replace an element from the specified element. |
15 | subList(intfromIndex, inttoIndex) | It is used to get elements from the specified range. |
16 | toArray(T[] a) | It is used to get all elements of the list in a proper sequence. |
17 | toString() | It is used to get string representation of the list |
Example:
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
class CopyOnWriteArrayListDemo1 extends Thread {
static CopyOnWriteArrayListobj = new CopyOnWriteArrayList();
public void run()
{
obj.add("Green");
}
public static void main(String[] args) throws InterruptedException
{
obj.add("Red");
obj.add("Blue");
obj.add("Pink");
CopyOnWriteArrayListDemo1 obj1 = new CopyOnWriteArrayListDemo1 ();
obj1.run();
Thread.sleep(1000);
Iterator a = obj.iterator();
while (a.hasNext())
{
String s = (String)a.next();
System.out.println(s);
Thread.sleep(1000);
}
System.out.println(obj);
}
}