jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Iterator confuson Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Iterator confuson" Watch "Iterator confuson" New topic

Iterator confuson

Kurt Harless

Joined: Feb 25, 2009
Posts: 8
OK. Trying to get a grip on collections and although iterating through using a FOR statement makes sense, using the iterator method confuses me.
How do I reference tempDog.getName() using an iterator in the below snippet;

Harshit Rastogi
Ranch Hand

Joined: Apr 15, 2008
Posts: 131
Iterator.next() first gives the current element and then traverse the pointer to the next element in the Iterator. Then iterator.hasnext() checks whether the element is present or not.

Note : pointer is not the C pointer

My Techie Blog - Java Questions
Kurt Harless

Joined: Feb 25, 2009
Posts: 8
OK... I may have figured it out;

This works, but looks kindof ugly!

Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

It's the first time I see an Iterator used with a for loop, but I still have lots to learn I usually prefer using a while loop instead.

Moreover, you are iterating through a list of Dog instances, so you should take advantage of Java's Generics here. Instead of declaring an Iterator of ?, you should use an Iterator of Dog. No need to cast then.

Anyway, using an enhanced for loop would do the same, but would be even more concise :

[My Blog]
All roads lead to JavaRanch
Rob Spoor

Joined: Oct 27, 2005
Posts: 20274

Harshit Rastogi wrote:Note : pointer is not the C pointer

That's why Java calls them references

How To Ask Questions How To Answer Questions
I agree. Here's the link: http://aspose.com/file-tools
subject: Iterator confuson
It's not a secret anymore!