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 ?

2 Answers 2

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");
 }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.