I'm trying to make use of the for each 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 im getting when using the for each 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)