aspose file tools*
The moose likes Beginning Java and the fly likes How iterator works? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How iterator works?" Watch "How iterator works?" New topic
Author

How iterator works?

Mallik Avula
Ranch Hand

Joined: Nov 30, 2006
Posts: 86
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?


Thanks & Regards<br />Mallik Avula<br />SCJP1.4
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Mallik Avula
Ranch Hand

Joined: Nov 30, 2006
Posts: 86
Thank you Peter n Rob
yes, i am asking about Iterator but Thinking in mind about Enumerator k
any how i got the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How iterator works?