Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How iterator works?

 
Mallik Avula
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI friends
I have a doubt,
i have a collection say ArrayList then i get an Iterator for it.
in a loop i am removing from the collection.
does that iterator effects?
example:

Collection col = new ArrayList();
Iterator itr = col.iterator();
while(itr.hasMoreElements()){
col.remove(obj);
}
this is not exactly my case but like this?
How iterator wotks in this case?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It doesn't. You can't directly modify the collection while iterating. You'll get a ConcurrentModificationException.

The one exception is that you can remove from the collection, by using the remove() method of Iterator, not the remove() method of the collection. Supporting remove() in an Iterator implementation is optional, but ArrayList does support it.

Note that you have written hasMoreElements(), but Iterator has no such method; it is hasNext(). You're thinking of Enumeration, which is mostly obsolete.
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, always call itr.next() in your loop. It's best to make it the first statement of your loop body.
If you forget, then calling itr.remove() will throw an exception. Even worse, if you forget and don't try to remove anything, your program will hang until you kill it.
 
Mallik Avula
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Peter n Rob
yes, i am asking about Iterator but Thinking in mind about Enumerator k
any how i got the answer.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic