user1203092
user1203092

Reputation: 41

java: delete elements from arraylist while using iterator

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?

Upvotes: 0

Views: 1040

Answers (1)

Mark Byers
Mark Byers

Reputation: 839144

Yes, you should use the remove method 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 calling remove on the iterator will work correctly (if it is implemented).

Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling [remove].


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:

Upvotes: 2

Related Questions