| Author |
Iterator confuson
|
Kurt Harless
Greenhorn
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
|
<a href="http://technologiquepanorama.wordpress.com" target="_blank" rel="nofollow">My Techie Blog</a><br /><a href="http://www.java-questions.com" target="_blank" rel="nofollow">Java Questions</a>
|
 |
Kurt Harless
Greenhorn
Joined: Feb 25, 2009
Posts: 8
|
|
OK... I may have figured it out;
This works, but looks kindof ugly!
|
 |
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14669
|
|
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
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Harshit Rastogi wrote:Note : pointer is not the C pointer
That's why Java calls them references
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Iterator confuson
|
|
|