tags:

views:

142

answers:

2

As in C++ iterator.remove() is not 100% safe or robust does java guarantees 100% robustness with iterator.remove()?

+2  A: 

Going off of matt's comment (who really deserves the credit)

http://java.sun.com/javase/6/docs/api/java/util/Iterator.html#remove%28%29

says:

void remove()

Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. 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 this method.

So...... yes, there are conditions under which unexpected/unsafe behaviour can occur.

Jonathan Fingland
can you please tell me what do mean by modification exactly
Ashish Agarwal
if you have a collection, and you get an iterator to that collection, but then modify the collection in someway before you are done using the iterator (without using the iterators methods), when you next attempt to use the iterator, you may get garbage.
Carl
specifically, modification in this case means addition of elements to or removal of elements from the underlying collection (not going through the Iterator to make the change). e.g. while iterating, you remove the third element in the collection and thus the iterator's understanding of the collection is (potentially) now out of sync with reality. How does the iterator deal with the change? It could skip an element, it could try to refer to the element that no longer exists, etc...
Jonathan Fingland
+2  A: 

Yes, it's robust in that it's defined on the interface and thus has to work on any collection where it's implemented. However, there are several caveats that come from the Javadoc:

  • It's an optional operation - not all things that provide an Iterator need to implement remove()
  • It can only be called once for every call to next()
  • It's not reliable if the underlying collection is modified during enumeration other than by calling remove()
Tim
can you please tell me what do mean by modification exactly
Ashish Agarwal
If the underlying collection is modified, a ConcurrentModificationException should be thrown.
pkaeding
Also, modification in this case means using the add or remove (or similar) methods on the List, Set, etc that the iterator is based on.
pkaeding
Yes, but the ConcurrentModificationException is not at all guaranteed, but implementations should throw it on a best-effort basis.
Henning