0

I have some code. It used to be like this,

for(Shape s: shapes){
g.setColor(Color.blue);
    g.fill(sh);
    g.setColor(Color.gray);
    g.draw(sh);
}

but it threw a ConcurrentModificationException, so I changed it to use iterators like this,

Iterator<Shape> s = shapes.iterator();
while(s.hasNext()){
Shape sh = s.next();
g.setColor(Color.blue);
    g.fill(s);
    g.setColor(Color.gray);
    g.draw(s);
}

but it still throws a ConcurrentModificationException. Maybe it's because it gets called in the paint method, but that's because it is when it gets drawn.

Hello World
  • 395
  • 3
  • 7
  • 3
    You need to show more of the `more code here`, especially the line that throws the exception. That information is pretty critical. Since you don't know what is causing your problem, you're liable to guess wrong with the code that you show us, so err slightly on the too much code than the too little. – Hovercraft Full Of Eels Feb 17 '15 at 22:00
  • What are you doing in the `more code here` section? – austin wernli Feb 17 '15 at 22:01
  • 1
    We need `more code here`. Also take a look at [Iterating through a list, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing) – Pshemo Feb 17 '15 at 22:01
  • are you trying to change 's' while iterating? that will throw an error unless you use fail safe iterator – Rusheel Jain Feb 17 '15 at 22:03
  • @RusheelJain In `for(Shape s: shapes)` changing `s` should be fine, but changing `shapes` not. In `Iterator s = shapes.iterator(); while(s.hasNext()){ Shape sh = s.next(); ....}` we can also change `s`. – Pshemo Feb 17 '15 at 22:04
  • 2
    I hope your *real* second code block isn't `g.fill(s);`, but rather is `g.fill(sh);` Are you sure that this is the code causing the exception? Have you inspected your stacktrace for the line? I suspect that your problem lies elsewhere. 1) Please post your exception's stacktrace. 2) Indicate in your code what line throws the exception. – Hovercraft Full Of Eels Feb 17 '15 at 22:06

1 Answers1

2

It's throwing that exception because in the "more code here" part, you're modifying (adding to or removing from) shapes.

If you use an Iterator, you may call:

s.remove();

but that's all.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • I'm only painting the shapes to the JPanel. – Hello World Feb 17 '15 at 22:06
  • 1
    Check what methods are being called from your code block and see what they're doing, and check if the JPanel has a reference to your object and is calling methods like `addShape()` etc. the CME is only thrown when you call `next()`, but another thread may have modified the collection between calls to `next()`. Try debugging your code setting a break point on all code that modified the collection. – Bohemian Feb 17 '15 at 22:13