Read Also : Array vs ArrayList in Java
Difference between ArrayList and CopyOnWriteArrayList in Java
1. Synchronization : ArrayList is not synchronized . CopyOnWriteArrayList is synchronized . Synchronization means at a time only one thread can access the object.
2. Performance : ArrayList is faster as it is not synchronized. That means many threads can execute the same piece of code simultaneously. In comparison , CopyOnWriteArrayList is slower.
3. Fail-fast vs Fail-safe : Iterators returned by ArrayList's iterator and listiterator methods are fail-fast. CopyOnWriteArrayList uses fail-safe iterator . We have already shared the fail-fast vs fail-safe iterators in java with example
4. ConcurrentModificationException : ArrayList can throw ConcurrentModificationException while CopyOnWriteArrayList can not .
5. Added in java version : ArrayList class was added in java version 1.2 , while CopyOnWriteArrayList class was added in java version 1.5 (or java 5) .
6. Package : ArrayList class is present in java.util package , while CopyOnWriteArrayList class is present in java.util.concurrent package.
Example of ArrayList and CopyOnWriteArrayList in Java
Output : ArrayList object output :[Alive is awesome, Love yourself]
CopyOnWriteArrayList object output :[Alive is awesome, Love yourself]
Similarities between ArrayList and CopyOnWriteArrayList
1. Permit null values : Both ArrayList and CopyOnWriteArrayList permits null.
2. Java Collections Framework : Both classes are part of the Java Collections Framework.
3. Clone method : Both classes clone method return the shallow copy of the original object.
When to prefer CopyOnWriteArrayList over ArrayList
So, if your code involves multi-threading tasks then prefer CopyOnWriteArrayList over ArrayList .
Otherwise , always use ArrayList .
Recap : Difference between ArrayList and CopyOnWriteArrayList in Java
|Iterator type||Fail fast iterator||Fail safe iterator|
|Performance||Fast||Slow in comparision|
|Added||Java 1.2||Java 1.5|
If you have any other questions or doubts regarding the difference between ArrayList and CopyOnWriteArrayList in Java , please mention in comments.