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
You can not remove or add objects from/to a collection you iterate on.
vecForShapes.remove(currentNode);for instance modifiesvecForShapes. Thus you get your exception.If I were you I would have done the modification you want like that:
This should do what you want without any error.
PS: do you really mean
Vector? I seriously recommend usingArrayListinstead. It is significantly better performant.