Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Iterator can safely remove?

 
Steven Zeng
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Paul Villangca
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,Paul,thank u!
 
Steven Zeng
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like this for instance:

Output is:
[hello1, hello2, hello4]
[ August 28, 2002: Message edited by: Valentin Crettaz ]
 
Steven Zeng
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the code runs. By the way,can anybody give a fail-fast example?Thanks in advance!
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic