-1

I have a foreach loop iterating through each object in a vector. When I debug the code, it runs successfully for the first object in the vector. But then it will fail when it tries to run the loop for the second object. I am sure there is more than one element in the vector.

for(Object shape : vecForShapes)
        {
            currentNode = (Drawable) shape;
             newNode = getResources().getDrawable(R.drawable.nodered);
             newNode.setBounds(currentNode.getBounds());
             vecForShapes.remove(currentNode);
              vecForShapes.add(newNode);
        }   

So basically my question is, why is this loop failing? I really do not understand what is wrong here.

P.S. My final aim is to remove currentNode from the vector, replace it with newNode then redraw the whole vector in my onDraw method.

Thanks

Leigh
  • 28,765
  • 10
  • 55
  • 103
James Hatton
  • 676
  • 2
  • 9
  • 28

2 Answers2

8

You can not remove or add objects from/to a collection you iterate on. vecForShapes.remove(currentNode); for instance modifies vecForShapes. Thus you get your exception.

If I were you I would have done the modification you want like that:

for (int i = 0; i < vecForShapes.size(); i++) {
     currentNode = (Drawable) shape;
     newNode = getResources().getDrawable(R.drawable.nodered);
     newNode.setBounds(currentNode.getBounds());
     vecForSahpes.set(i, newNode);
}

This should do what you want without any error.

PS: do you really mean Vector? I seriously recommend using ArrayList instead. It is significantly better performant.

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • Vector is better when data increases exponentially and it is thread safe. But yes most of other cases I will use ArrayList too – ziq Mar 11 '12 at 20:47
  • Thanks a lot you were correct....I didn't know I could not remove or add from a collection when iterating... I will definately take a look now at arraylist...thanks for the tips!! – James Hatton Mar 11 '12 at 22:04
1

When using foreach on an Iterable, there would be an Iterator behind the scenes and you can not modify a Collection when iterating over it, but you can call "iterator.remove()". So I recommend you to use old iteration model for (Iterator i = v.iterator(); i.hasNext(); ..... and call the i.remove() on it.

Amir Pashazadeh
  • 7,170
  • 3
  • 39
  • 69