Iterator can safely remove?

Here is question : Collection interface iterator method returns Iterator(like Enumerator), through you can traverse a collection from start to finish and safely remove elements. A) true B) false The answer is A,but I know that the iterator method returns Iterator that is fail-fast, so i doubt this answer,is it CORRECT?

Hi Steven, From the all-knowing API: public Object next() Returns the next element in the iteration. public void remove() Removes from the underlying collection the last element returned by the iterator (optional operation). You can traverse the collection with next(), and remove elements with remove(). Fail-fast just means you can't modify the collection outside of the iterator (i.e., modifying the collection directly) during iteration, you can still traverse/remove elements through the iterator.

Steven Zeng
Ranch Hand

Joined: Jan 15, 2002
Posts: 41

posted Aug 28, 2002 19:45:00

0

Hi,Paul,thank u!

Steven Zeng
Ranch Hand

Joined: Jan 15, 2002
Posts: 41

posted Aug 28, 2002 20:28:00

0

Given a Vector containing several elements, if we want to loop over it and remove some element under specific condition,should a Iterator achieve this goal?How to do?

Yes, the code runs. By the way,can anybody give a fail-fast example?Thanks in advance!

Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610

posted Aug 29, 2002 00:14:00

0

We can use the same code and try to remove an element from the vector within the while-loop by invoking remove on the vector directly.

Output: Exception in thread "main" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:444) at java.util.AbstractList$Itr.next(AbstractList.java:417) at tr.main(tr.java:16) This means that while you are iterating over a vector, there is no way that the vector may be structurally modified by any other thread having a reference to that vector.