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
2009-10-03 15:48:13
can you please tell me what do mean by modification exactly
Ashish Agarwal
2009-10-03 15:53:00
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
2009-10-03 16:51:34
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
2010-08-19 20:30:35
+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
2009-10-03 15:48:46
If the underlying collection is modified, a ConcurrentModificationException should be thrown.
pkaeding
2009-10-03 15:55:00
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
2009-10-03 15:56:03
Yes, but the ConcurrentModificationException is not at all guaranteed, but implementations should throw it on a best-effort basis.
Henning
2009-10-03 16:18:28