• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2808
  • Last Modified:

avoiding java.util.ConcurrentModificationException in for loops

What is the best way to avoid java.util.ConcurrentModificationException in the for loop below:

import java.util.Collection;
import java.util.Iterator;
import java.util.TreeSet;

import junit.framework.TestCase;

public class Test extends TestCase {


 
   public void testLoop()
   {
      Collection currentCollection = new TreeSet();
      currentCollection.add("AAA");
      currentCollection.add("BBB");
      currentCollection.add("CCC");
     
      Collection updatedCollection = new TreeSet();
      updatedCollection.add("CCC");
      updatedCollection.add("DDD");
      updatedCollection.add("EEE");
     
      for (Iterator iter = currentCollection.iterator(); iter.hasNext();) {
         String element = (String) iter.next();
         if(!updatedCollection.contains(element))
         {
            currentCollection.remove(element);
         }
         
      }
      assertTrue(currentCollection.contains("DDD"));
      assertTrue(currentCollection.contains("EEE"));
      assertFalse(currentCollection.contains("CCC"));
     
   }
   
}
0
aturetsky
Asked:
aturetsky
  • 2
1 Solution
 
CEHJCommented:
Try changing

>>currentCollection.remove(element);

to

iter.remove();
0
 
aturetskyAuthor Commented:
great, thanks !
0
 
CEHJCommented:
:-)
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now