• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

How iterator works?

 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22716
129
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic