wood burning stoves 2.0*
The moose likes Java in General and the fly likes Please help me understand Iterator - I am a beginner and I did a reserch but I didn't find an answer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Please help me understand Iterator - I am a beginner and I did a reserch but I didn Watch "Please help me understand Iterator - I am a beginner and I did a reserch but I didn New topic
Author

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

André Asantos
Ranch Hand

Joined: Nov 23, 2009
Posts: 234
I am looking for some exemples that say how to use Iterator interface, iterator() method, next() and hasNext() methods...


thanks a lot,
AS


André AS
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
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

Joined: Nov 23, 2009
Posts: 234
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?


Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13875
    
  10

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?

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Please help me understand Iterator - I am a beginner and I did a reserch but I didn't find an answer
 
Similar Threads
Help with book exame numbers
Overriding remove method of an iterator
T- Shirt Quotes
Need help in JSP
another question from scjptest.com