Solved

avoiding java.util.ConcurrentModificationException in for loops

Posted on 2006-06-13
3
2,749 Views
Last Modified: 2007-12-19
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
Comment
Question by:aturetsky
  • 2
3 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 250 total points
ID: 16897118
Try changing

>>currentCollection.remove(element);

to

iter.remove();
0
 
LVL 1

Author Comment

by:aturetsky
ID: 16898009
great, thanks !
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16898060
:-)
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This video teaches viewers about errors in exception handling.

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question