aspose file tools*
The moose likes Performance and the fly likes Which loop is recommended for getting values from list? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "Which loop is recommended for getting values from list? " Watch "Which loop is recommended for getting values from list? " New topic
Author

Which loop is recommended for getting values from list?

ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
Which loop is recommended for retrieving values from a list - for or while. I like while loop with iterator, but can't force my whole team to use that because don't have justification to this...

Please help me out.
Thanks a lot.
[ June 17, 2005: Message edited by: rathi ji ]
Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
I won't have thought that you need to force people to adopt a particular style for this, there are usually far more important things to worry about. For what it is worth, my way of coding is like this:


SCJP 1.4, SCWCD 1.3, SCBCD 1.3
Tim West
Ranch Hand

Joined: Mar 15, 2004
Posts: 539
IMO it is reasonable for a coding standard to mandate a particular style. I agree with Roger on the choice: 'for' is much better in this case. Consider the following:



There is a bug in this which is obvious when you're looking for it, but can be missed if you're not. That is, in the second while() loop, we're using the wrong iterator. This is often a copy/paste error - and not necessarily an obvious one one, since the iterator 'iter' has no more elements, so the second while() loop is silently skipped.

If this code is written using for() loops, the scope of the Iterator prevents this error from occurring.

That all said, this has nothing to do with performance...it's a matter of coding style


-Tim
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
Thanks a lot.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Notice that in Java 5, the "right" thing to do is


[ June 21, 2005: Message edited by: Ilja Preuss ]

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Which loop is recommended for getting values from list?
 
Similar Threads
how to print only strings using generics when the list is having multiple types
Moving Shapes between two Points
iterate
passing parameters from JSP to a Servlet
create multiple Checkboxes with data base values in jsp