Last Updated : 11 Dec, 2018
Both
ArrayListand
CopyOnWriteArrayimplement List interface. But There are lots of differences between ArrayList and CopyOnWriteArrayList:
// Java program to illustrate ArrayList
import java.util.*;
class CopyDemo
{
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"))
{
// Can remove
itr.remove();
}
}
System.out.println(l);
}
}
Output:
[A,C]JAVA
// Java program to illustrate CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
class CopyDemo 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4