I use a list of objects, each object contains a number and a string name. when a object with the same name is twice in my list i update the number of one of them by 1 and delete the other one, so far so good.
but when i delete a object from this list the iterator still brings back the one i just deleted, it is not in the list anymore, but still has the same location i think.
example:
x 1;
x 1;
y 1;
z 1;
i delete the second x and update the count of the other one:
x 2;
y 1;
z 1;
But now the iterator brings me back the x 1 which was at position two in the beginning, for the iterator it still looks like this:
x 1;
[x1];
y 1;
z 1;
(At least this is what i think what happens, trying it for a few hours now..)
Is there any way to tell the iterator that the list has changed ?
i just read about an remove() method of the iterator, am i right here?
Yes, you should use the
removemethod on the iterator to remove the item from the collection, rather than removing the item from the collection directly. In general if you add or remove elements while you are iterating over the collection, then the iterator will no longer work correctly. However callingremoveon the iterator will work correctly (if it is implemented).As a side note, the actual problem you are trying to solve seem to be very similar to the one in this question, so you may also want to look at the answers here for alternative (simpler) approaches: