• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Please help me understand Iterator - I am a beginner and I did a reserch but I didn't find an answer

 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am looking for some exemples that say how to use Iterator interface, iterator() method, next() and hasNext() methods...


thanks a lot,
AS
 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Tbh. I think you didn't look really hard...a simple search of "java iterator" on google returns multiple examples...

Anyway, usage is fairly simple. If you have a class that implements the "Iterator" interface (like most of the Collection classes), you
1) obtain the Iterator by calling the iterator() method of the collection
2) you loop over the collection using the hasNext() method of the Iterator
3) in the loop body, you obtain the current element by using the next() method of the Iterator (you will likely have to cast to the type of the objects in the collection)
4) then you can use the object normally. Note: if if you want to call the remove() method of the Iterator, you will have to make sure no other threads access the collection at the same time (synchronisation)!
 
André Asantos
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello to you D. Ogranos,

you were right I did not do a good researching... now I did that and found following:

source: Sun docs, from what I have understood the Iterator interface has 3 methods only remove(), hasNext() and Next(), right?


 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

André Asantos wrote:source: Sun docs, from what I have understood the Iterator interface has 3 methods only remove(), hasNext() and Next(), right?


If that's what the Sun docs say, then that's what it is - why do you want extra confirmation?
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic