title: ConcurrentModificationException when adding inside a foreach loop in ArrayList
body: <p>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?</p>
  
  <p>The code is here: </p>
  
  <pre><code>for (Pair p2 : R) {
      if ((p2.getFirstElm() == p.getSecondElm()) &amp;&amp; (p2.getFirstElm() != p2.getSecondElm())) 
          R.add(new Pair (p.getFirstElm(), p2.getSecondElm()));
      else if ((p2.getSecondElm() == p.getFirstElm()) &amp;&amp; (p2.getFirstElm() != p2.getSecondElm())) 
          R.add(new Pair (p2.getFirstElm(), p.getSecondElm()));
  
      // else
      // There are no transitive pairs in R.
  }
  </code></pre>
  
  <p>this is the loop that doesnt work, and here is the one that works:</p>
  
  <pre><code>for (int i = 0; i &lt; R.size(); i++) {
      if ((R.get(i).getFirstElm() == p.getSecondElm()) &amp;&amp; (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()) &amp;&amp; (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.
  }
  </code></pre>
  
  <p>the error I'm getting when using the foreach loop is:</p>
  
  <pre><code>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)
  </code></pre>