Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentModificationException when adding inside a foreach loop in ArrayList [duplicate]

Tags:

People also ask

How do I fix Java Util ConcurrentModificationException?

How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.

Can you use a forEach loop on an ArrayList?

As of Java 8, we can use the forEach method as well as the iterator class to loop over an ArrayList.

What happens if ArrayList is concurrently modified while iterating the elements?

The ConcurrentModificationException occurs when an object is tried to be modified concurrently when it is not permissible. This exception usually comes when one is working with Java Collection classes. For Example - It is not permissible for a thread to modify a Collection when some other thread is iterating over it.


I'm trying to make use of the foreach loop with the arraylist, but when I use it, it gives me error, but when I use normal for loop, it works perfectly, what could be the problem?

The code is here:

for (Pair p2 : R) {     if ((p2.getFirstElm() == p.getSecondElm()) && (p2.getFirstElm() != p2.getSecondElm()))          R.add(new Pair (p.getFirstElm(), p2.getSecondElm()));     else if ((p2.getSecondElm() == p.getFirstElm()) && (p2.getFirstElm() != p2.getSecondElm()))          R.add(new Pair (p2.getFirstElm(), p.getSecondElm()));      // else     // There are no transitive pairs in R. } 

this is the loop that doesnt work, and here is the one that works:

for (int i = 0; i < R.size(); i++) {     if ((R.get(i).getFirstElm() == p.getSecondElm()) && (R.get(i).getFirstElm() != R.get(i).getSecondElm()))          R.add(new Pair (p.getFirstElm(), R.get(i).getSecondElm()));     else if ((R.get(i).getSecondElm() == p.getFirstElm()) && (R.get(i).getFirstElm() != R.get(i).getSecondElm()))          R.add(new Pair (R.get(i).getFirstElm(), p.getSecondElm()));     //else     //  There are no transitive pairs in R. } 

the error I'm getting when using the foreach loop is:

Exception in thread "main" java.util.ConcurrentModificationException     at java.util.AbstractList$Itr.checkForComodification(Unknown Source)     at java.util.AbstractList$Itr.next(Unknown Source)       at set.problem.fourth.PoSet.makeTransitive(PoSet.java:145)       at set.problem.fourth.PoSet.addToR(PoSet.java:87)     at set.problem.fourth.PoSetDriver.typicalTesting(PoSetDriver.java:35)     at set.problem.fourth.PoSetDriver.main(PoSetDriver.java:13)