Created
August 26, 2012 14:40
-
-
Save uttesh/3480462 to your computer and use it in GitHub Desktop.
CopyOnWriteArrayList difference with normal ArrayList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.concurrent.CopyOnWriteArrayList; | |
/* | |
* Difference between ArrayList and CopyOnWriteArrayList | |
*/ | |
public class CopyOnWriteArrayListTest { | |
public static void main(String[] args) { | |
CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList(); | |
copyOnWriteArrayList.add("copyOnWriteArrayList_item"); | |
copyOnWriteArrayList.add("copyOnWriteArrayList_item1"); | |
Iterator iCopyIterator = copyOnWriteArrayList.iterator(); | |
while (iCopyIterator.hasNext()) { | |
//System.out.println(iCopyIterator.next()); | |
iCopyIterator.next(); | |
copyOnWriteArrayList.add("copyOnWriteArrayList_item2"); | |
} | |
System.out.println("|---- After modification of copyOnWriteArrayList ----| "); | |
Iterator i2 = copyOnWriteArrayList.iterator(); | |
while (i2.hasNext()) { | |
System.out.println(i2.next()); | |
} | |
/* | |
* If List modified in the loop iteration it will throw | |
* ConcurrentModificationException or if multiple threads try to modify | |
* the List in loop iteration will throw the exception for normal arrayList | |
*/ | |
List list = new ArrayList(); | |
list.add("test"); | |
list.add("test1"); | |
Iterator listIterator = list.iterator(); | |
while (listIterator.hasNext()) { | |
System.out.println(listIterator.next()); | |
list.add("test2"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment