0

I am trying to add an String object into ArrayList<String> while iterating it. then i have a Exception like :

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at com.alonegk.corejava.collections.list.ArrayListDemo.main(ArrayListDemo.java:19)

the piece of code as -

public static void main(String[] args) {
    ArrayList<String> al =new ArrayList<String>();

    al.add("str1");
    al.add("str2");

    Iterator<String> it = al.iterator();

    while(it.hasNext()){
        System.out.println(it.next());
        al.add("gkgk");

    }

there is no synchronization here. i need to know the cause of this exception ?

Greesh Kumar
  • 1,847
  • 3
  • 27
  • 44

2 Answers2

3

Refer this for ConcurrentModificationException.Try using ListIterator<String> if you want to add new value in the iterator.

public static void main(String[] args) {
ArrayList<String> al =new ArrayList<String>();

al.add("str1");
al.add("str2");

ListIterator<String> it = al.listIterator();

while(it.hasNext()){
    System.out.println(it.next());
    it.add("gkgk");
 }
}
Community
  • 1
  • 1
additionster
  • 628
  • 4
  • 14
1

The ConcurrentModificationException is used to fail-fast when something we are iterating and modifying at the same time

we can do the modification by using iterator directly as

 for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) {
    Integer integer = iterator.next();
    if(integer == 2) {
        iterator.remove();
    }
}
Arun Kumar
  • 91
  • 1
  • 7