0

Possible Duplicate:
ConcurrentModificationException and a HashMap

I am getting the following exception

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.TreeMap$PrivateEntryIterator.nextEntry(Unknown Source)
at java.util.TreeMap$KeyIterator.next(Unknown Source)
at Types$AdjList.makeConnected(Types.java:281)
at Main.main(Main.java:56)

while executing the following code

public void makeConnected() {
        TreeSet<Node> exploredNodes = new TreeSet<Node>();
        TreeSet<Node> unexploredNodes = new TreeSet<Node>();
for (Node n : unexploredNodes) {
        ...
        exploredNodes.add(n);
        unexploredNodes.remove(n);
        ...
}

I am not using the iterator like in HashMap but need to use a Set that may grow or reduce based on some condition. I will accept and give points to all answers. Look forward to how to replies on how to solve this problem of ConcurrentModificationException Thanks, Somnath

Community
  • 1
  • 1
somnathchakrabarti
  • 3,026
  • 10
  • 69
  • 92

1 Answers1

4

The for loop internally uses iterators and you are not removing the elements using the iterator. Hence, the problem. Use iterator's remove method as below:

for (Iterator iterator = exploredNodes.iterator(); iterator.hasNext();) {
     Node n = (Node) iterator.next();
     unexploredNodes.add(n);         
     iterator.remove();
}
Drona
  • 6,886
  • 1
  • 29
  • 35
  • I am not being able to use the iterator.hasNext(). It is popping a message:The method hasNext() is undefined for the type HTMLDocument.Iterator – somnathchakrabarti Mar 24 '12 at 21:10