File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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?

Collection col = new ArrayList();
Iterator itr = col.iterator();
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

Joined: Oct 27, 2005
Posts: 20276

Also, always call 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.

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.
It is sorta covered in the JavaRanch Style Guide.
subject: How iterator works?
It's not a secret anymore!