• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Iterator confuson

 
Kurt Harless
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Kurt Harless
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK... I may have figured it out;

This works, but looks kindof ugly!

 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 :

 
Rob Spoor
Sheriff
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Harshit Rastogi wrote:Note : pointer is not the C pointer

That's why Java calls them references
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic