Greesh Kumar
Greesh Kumar

Reputation: 1888

Exception when adding element to ArrayList while iterate

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 ?

Upvotes: 0

Views: 152

Answers (2)

Arun Kumar
Arun Kumar

Reputation: 127

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();
    }
}

Upvotes: 1

additionster
additionster

Reputation: 628

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");
 }
}

Upvotes: 3

Related Questions