Loading...
Logo
Processing Forum
I get a ConcurrentModificationException and the problem seems to be line 17.
Cause if i comment it out i have no errors.

Copy code
  1. else if(ctrl) {
  2.                 // TOGGLE
  3.                 HashSet<CVector> selection = new HashSet<CVector>();
  4.                
  5.                 System.out.println("A");
  6.                
  7.                 for (Layer layer : toolHandler.layerStack.layers) {
  8.                     selection.addAll(selection(x1, y1, x2, y2, layer));
  9.                 }
  10.                 System.out.println("B");
  11.                
  12.                 Iterator<CVector> itr = selection.iterator();
  13.                 while(itr.hasNext()) {
  14.                     CVector v = itr.next();
  15.                     if(toolHandler.layerStack.anchorSelection.contains(v)) {
  16.                         toolHandler.layerStack.anchorSelection.remove(v);
  17.                         selection.remove(v);
  18.                     }
  19.                 }
  20.                 System.out.println("C");
  21.                
  22.                 toolHandler.layerStack.anchorSelection.addAll(selection);
  23.                
  24.             }

hope some one can help

Replies(3)

Hi clankill3r!
Just used iterators myself once or twice. But let's have a wild guess! 
According to official Oracle's Java docs -> Iterator
There are only 3 methods to interface Iterator -> hasNext(), next() & remove().
And none of them uses any parameters!

Thus, in the point of view of an Iterator, selection.remove(v); is already wrong!!!  
B/c method remove() doesn't use parameters & selection is not an instance of type Iterator!

Of course, class HashSet has its own method remove(Object o). And that's exactly what you have tried to use.
However, if you remove an element of your HashSet w/o using an Iterator, while iterating over it within a loop,
you get -> ConcurrentModificationException!

An alternative algorithm to remove an element w/o relying on an Iterator is by making a backwards loop instead.

I believe replacing selection.remove(v); w/ itr.remove(); should be enough to avoid that error.
But since I can't run your code due to lack of classes CVector & toolHandler;
only you can tell us whether it got fixed or not!
thanks, kinda make sense.
itr.remove();

did the trick!

kinda make sense...
Don't forget to re-read my answer post.
I was editing it non-stop, explaining why the answer would be that!