File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How iterator works?

 
Mallik Avula
Ranch Hand
Posts: 86
  • 0
  • 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
  • 0
  • 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: 20369
44
Chrome Eclipse IDE Java Windows
  • 0
  • 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
  • 0
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic