Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why is it so  RSS feed

 
Mohit Agarwal
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

According to Sun Java Tutorial,

Use Iterator instead of the for-each construct when you need to:
Iterate over multiple collections in parallel.

Whats the benefit in case we go with the iterator?

Please provide your inputs on this..

Thanks,
Mohit.
 
Srinivas Kalvala
Ranch Hand
Posts: 257
Firefox Browser Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

The Advantage with iterator is you can get list of objects irrespective of the data structure. if you use for loop then you have to write a seperate for loop for data structure.

Do one thing ...

Search with following Key word in Google:

Iterator Design Pattern

or

http://www.google.co.in/search?hl=en&q=Iterator+Design+pattern&meta=
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think that answers the question at all.

The answer is that when using "for/each", you don't actually have access to the Iterator; the loop construct looks directly at the collection or array itself. So let's say you need to do something like this:



Do you see how we're using the loop counter to access two different arrays? You can't do that with a single for/each loop; you'd have to write two loops. Therefore, don't use for/each when you need to iterate over multiple collections -- because you can't!
 
Srinivas Kalvala
Ranch Hand
Posts: 257
Firefox Browser Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are Right,

But my intention was, to make him think about the Iterator pattern so that he can get more ...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!