Difference between ArrayList and CopyOnWriteArrayList
Both ArrayList and CopyOnWriteArray implement List interface. But There are lots of differences between ArrayList and CopyOnWriteArrayList:
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" ))
{
itr.remove();
}
}
System.out.println(l);
}
}
|
Output:
[A,C]
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" ))
{
itr.remove();
}
Thread.sleep( 1000 );
}
System.out.println(l);
}
}
|
Output:
A
B
Exception in thread "main" java.lang.UnsupportedOperationException
Last Updated :
11 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...