File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Difficults using Iterator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difficults using Iterator" Watch "Difficults using Iterator" New topic

Difficults using Iterator

André Asantos
Ranch Hand

Joined: Nov 23, 2009
Posts: 234

Could you comment my code? I did not understand why I use while...
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

while loop is un-necessary here. your for loop do the same conditional check .

your way of iterating the elements in list is Ok . but I do suggest you to go for for-each loop which is introduced in java1.5 because it is simple to use.

David Newton

Joined: Sep 29, 2008
Posts: 12617

André Asantos wrote:I did not understand why I use while...

There's not much to say--"while" basically means "as long as". "As long as the iterator has more elements, do whatever is inside the block."
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

You're mixing up two ways of doing the same thing. Either of the following would work:

The second is probably easier to understand, but the first avoids the need to have a separate assignment statement, which I think is why some people use it.

The third approach, that Seetharaman gives above, is preferable to either of them, though.
David Newton

Joined: Sep 29, 2008
Posts: 12617

(Oh, I didn't even register the duplication, probably due to the random indentation.)
I agree. Here's the link:
subject: Difficults using Iterator
It's not a secret anymore!