Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2006

Tip: Looking for answers? Try searching our database.

Opinion poll: for loop vs while loop with Iterators.

Thread view: 
Daniel Pitts - 21 Dec 2006 20:40 GMT
Java 1.5 finaly gave us an elegant for each construct, but for-each
lacks the ability to manipulate the underlying Iterable structure.

Generally, the way to do this is (in pseudo-code:)

Obtain the iterator.
L: Check if it has a next element
get the next element
process the element.
repeat from L

This can be coded in Java a few ways.
// For method:
for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext(); )
{
  E e = iterator.next();
  if (shouldRemove(e)) {
     iterator.remove(e);
  }
}

// vs
// While method:
Iterator<E> iterator = iterable.iterator();
while (iterator.hasNext()) {
  E e = iterator.next();
  if (shouldRemove(e)) {
     iterator.remove(e);
  }
}

Both approaches have their pros and cons, but I'm interested to see
what people think.

I'll post my opinion later.
Karl Uppiano - 21 Dec 2006 20:54 GMT
> Java 1.5 finaly gave us an elegant for each construct, but for-each
> lacks the ability to manipulate the underlying Iterable structure.
[quoted text clipped - 31 lines]
>
> I'll post my opinion later.

I tend to use the while pattern for no particularly good reason except that
the increment expression is not used in the for pattern. I guess it offends
my sense of esthetics, which is reason enough to tip the balance, all else
being equal. I might change my mind if someone can demonstrate a big
advantage one way or the other.
Daniel Dyer - 21 Dec 2006 20:57 GMT
> Java 1.5 finaly gave us an elegant for each construct, but for-each
> lacks the ability to manipulate the underlying Iterable structure.
[quoted text clipped - 31 lines]
>
> I'll post my opinion later.

The for loop is one line shorter but I've always preferred the while  
loop.  It justs seems more natural and more readable to me.  When I was at  
school, programming in BASIC and Pascal with less flexible for loops, for  
loops were for a fixed number of iterations known at the start, and while  
loops for an indeterminate number of iterations.  With an iterator, you  
don't know how many iterations are required until you've finished (you can  
find out, but it's more work).  So reading code that says "while there are  
more elements do x" just seems more correct.

Dan.

Signature

Daniel Dyer
http://www.uncommons.org

bjeremy - 21 Dec 2006 22:45 GMT
> Java 1.5 finaly gave us an elegant for each construct, but for-each
> lacks the ability to manipulate the underlying Iterable structure.
[quoted text clipped - 31 lines]
>
> I'll post my opinion later.

In "Effective Java" by Josh Bloch (p. 142 for all those who wish to
check this), Josh argues that we should prefer using for loops as
opposed to while loops. His reasoning is that the loop structure allows
us an opportunity to limit the scope of variables. The for loop enables
us to declare loop variables and thus limit their scope to the exact
region needed. His caveat is if you happen to need the variable after
the execution of the loop, you probably don't want to make it a loop
variable.
Daniel Pitts - 21 Dec 2006 23:11 GMT
> > Java 1.5 finaly gave us an elegant for each construct, but for-each
> > lacks the ability to manipulate the underlying Iterable structure.
[quoted text clipped - 40 lines]
> the execution of the loop, you probably don't want to make it a loop
> variable.

My personal preference is the while loop.

I agree that limiting the scope of temporary variables is useful,
however, there are clearer ways to accomplish this.  My personal
favorite is to introduce a method that does the work of the loop. That
has the added benefit of explaining what the loop does, by giving it a
name.

Alternatively, to limit the scope other ways you can do stuff like:

public static void main(String...args) {
  {
     final int myInt = 0;
     System.out.println(myInt);
  }
  {
     final int myInt = 2;
     System.out.println(myInt);
  }
}
Lew - 22 Dec 2006 01:14 GMT
> My personal preference is the while loop.

I much prefer the for loop, except when there is no loop variable.

I notice that the sun rises and sets irrespective of my preference, though.

- Lew
Daniel Pitts - 22 Dec 2006 01:35 GMT
> > My personal preference is the while loop.
> I much prefer the for loop, except when there is no loop variable.

My opinion on the for statement:
It is useful when there are 2 simple statements (initializer and
post-loop), one conditional expression, and 1 more statement (compound
or otherwise)

The iterator concept does NOT fall into that category, unless you write
it like this:
E e;
for (Iterator<E> i = getIterator(); i.hasNext(); doSomething(e)) {
   e = i.next();
}

Which IMHO is ugly.

Although, like you said
> I notice that the sun rises and sets irrespective of my preference, though.
Happens to be true of me too.
bjeremy - 22 Dec 2006 02:24 GMT
> The iterator concept does NOT fall into that category, unless you write
> it like this:
[quoted text clipped - 4 lines]
>
> Which IMHO is ugly.

How's this then?

for (Iterator<E> i = getIterator(); i.hasNext(); ){
  doSomething(i.next());
}
Lew - 22 Dec 2006 03:39 GMT
> My opinion on the for statement:
> It is useful when there are 2 simple statements (initializer and
> post-loop), one conditional expression, and 1 more statement (compound
> or otherwise)

That use case lies far over toward the "for" end of the seesaw.

> The iterator concept does NOT fall into that category, unless you write
> it like this:
[quoted text clipped - 4 lines]
>
> Which IMHO is ugly.

That use case lives nearer the middle.

I happen to like that idiom, except that I declare "E e" inside the loop and
put the doSomething() there, too, but I understand perfectly well why it seems
ugly.

I rarely will put a workhorse expression inside the for () setup; they belong
in the body.

My version would be (assuming a collection as the progenitor of the iterator):

for ( Iterator<E> iter = collection.getIterator(); iter.hasNext(); )
{
  E entry = iterator.next();
  doSomething( entry ); // or just doSomething( iterator.next() )
}

In most cases, that becomes

for( E entry : collection )
{
  doSomething( entry );
}

anyway, and the ugliness vanishes very far.

>> I much prefer the for loop, except when there is no loop variable.

I lied. I use for() {}, while () {} and do {} while ();.

I prefer all three. I like "for ( ;; )" to set up unbounded loops.

- Lew
John Ersatznom - 22 Dec 2006 09:25 GMT
> I prefer all three. I like "for ( ;; )" to set up unbounded loops.

Yuck! I have always used (and usually see everyone else use) "while
(true)"...
Lew - 22 Dec 2006 13:22 GMT
>> I prefer all three. I like "for ( ;; )" to set up unbounded loops.

> Yuck! I have always used (and usually see everyone else use) "while
> (true)"...

Yuck? Here we have a perfectly useful idiom purpose-built to handle just this
situation. I wonder why that seems so hideous to you.

It's nice to have choices.

- Lew
Patricia Shanahan - 22 Dec 2006 15:26 GMT
>>> I prefer all three. I like "for ( ;; )" to set up unbounded loops.
>
[quoted text clipped - 7 lines]
>
> - Lew

The difference is that the first time I saw a "for(;;)" I had to think
to work out that it was going to loop forever. It depends on
understanding the effect of omitting the continuation test.

The first time I saw a "while(true)" it was instantly obvious that the
intent was to loop as long as true is true.

Patricia
Lew - 23 Dec 2006 04:29 GMT
> The difference is that the first time I saw a "for(;;)" I had to think
> to work out that it was going to loop forever. It depends on
> understanding the effect of omitting the continuation test.
>
> The first time I saw a "while(true)" it was instantly obvious that the
> intent was to loop as long as true is true.

You seem to imply that a computer language should be explicable to those who
do not know that language.

There is a case for that. OTOH, the for ( ;; ) idiom has been around for
decades and should be familiar to anyone versed in the C/Java family of languages.

OTOOH, I might switch to using while ( true ) myself for the very reason you
state.

OTOOOH, the for ( ;; ) construction is so ugly-cute, and ugly-clever, and
ugly-elitist, that I don't think I will ever give it up entirely.

- Lew
Patricia Shanahan - 23 Dec 2006 05:22 GMT
>> The difference is that the first time I saw a "for(;;)" I had to think
>> to work out that it was going to loop forever. It depends on
[quoted text clipped - 9 lines]
> decades and should be familiar to anyone versed in the C/Java family of
> languages.

"know the language" is not a binary state. I prefer my code to be
readable by as many people as possible.

I have trouble imagining someone understanding "for(;;)" but not
"while(true)". I'm not so sure the other way round.

Patricia
Ed - 22 Dec 2006 21:00 GMT
bjeremy skrev:

> In "Effective Java" by Josh Bloch (p. 142 for all those who wish to
> check this), Josh argues that we should prefer using for loops as
[quoted text clipped - 4 lines]
> the execution of the loop, you probably don't want to make it a loop
> variable.

Seconded, FWIW.

("Sun, arise!")

.ed

--

www.EdmundKirwan.com - Home of The Fractal Class Composition


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.