ArrayList & its feature ::
1. ArrayList class is an important class of Collection framework.
2. ArrayList extends generic AbstractList.
3. ArrayList implements generic List, RandomAccess, Cloneable and java.io.Serializable
4. ArrayList internally stores elements in a re-sizable array.The default capacity of array is 10 and it grows dynamically by 50% of its default capacity ,if number of element exceeds from its capacity.
5. ArrayList is roughly equivalent to Vector class except that it is unsynchronized i.e. it is not thread safe.But, it can be made synchronized explicitly like below
1 |
List<String> l = java.util.Collections.synchronizedList(new ArrayList<String>()); |
5. ArrayList can accept any element including multiple null values.
7. ArrayList uses Iterator interface to traverse the elements.While traversing the elements using iterator if the structure of the ArrayList is modified using add or remove method ,iterator will throw ConcurrentModificationException.So iterators for ArrayList are fail-fast.
Sample Program ::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.ai1tutorial.collection.arraylist; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListDemo { public static void main(String[] args) { List<String> arrayList = new ArrayList<String>(); arrayList.add("Ajay"); arrayList.add("Kumar"); arrayList.add("Mohanty"); Iterator<String> iterator = arrayList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } } |
Output ::
1 2 3 |
Ajay Kumar Mohanty |
Now let us see an example of ConcurrentModificationException.In the below program while iterating the ArrayList,i am modifying the structure of the ArrayList by adding a new element.So I am getting ConcurrentModificationException.
Example of ConcurrentModificationException ::
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.ai1tutorial.collection.arraylist; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListDemo { public static void main(String[] args) { List<String> arrayList = new ArrayList<String>(); arrayList.add("Ajay"); arrayList.add("Kumar"); arrayList.add("Mohanty"); Iterator<String> iterator = arrayList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); arrayList.add("Jyoti"); } } } |
Output ::
1 2 3 4 5 |
Ajay Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) at com.ai1tutorial.collection.arraylist.ArrayListDemo.main(ArrayListDemo.java:16) |