1.5 style "for" loops

C

Chanchal

hey,

can some one tell me what is the advantage of "for each" style loop in
1.5 over the conventional for loop
thanx

chanchal
 
A

Adam Maass

Chanchal said:
hey,

can some one tell me what is the advantage of "for each" style loop in
1.5 over the conventional for loop
thanx

chanchal

It's a briefer syntax:

Old style:

for(Iterator i = collection.iterator(); i.hasNext(); ;) {
Item item = (Item)i.next();
...
}


New style:

for(Item item: collection) {
...
}




IMHO, the new style is conceptually a bit cleaner as well: you're applying
the body of the loop to each item in the collection in turn. You don't have
to write code for the mechanics of getting that to happen.


-- Adam Maass
 
T

Thomas Hawtin

It's a briefer syntax:

And more consistent between array and non-RandomAccess Iterables.
Old style:

for(Iterator i = collection.iterator(); i.hasNext(); ;) {
Item item = (Item)i.next();
...
}

Which does conceptually the same thing as the completely different code:

final int num = array.length;
for (int ct=0; ct<num; ++ct) {
Item item = array[ct];
...
}

The new syntax does fall down if you want to remove items from an
iterator, replace items or use the index. But, say, 80% of the time it
just reads better.

Tom Hawtin
 
R

Roedy Green

can some one tell me what is the advantage of "for each" style loop in
1.5 over the conventional for loop

they both generate the same code. The for:each is terser and hence
easier to maintain and read.
 
B

Benji

they both generate the same code.

That's not necessarily true. Using a for:each gives the compiler more of
a chance to optimize the loop than it would with a standard for. (Of
course, whether or not it is optimized in the current compiler/VM is
another story)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top