Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes Regarding for-each loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Regarding for-each loop" Watch "Regarding for-each loop" New topic
Author

Regarding for-each loop

surya.raaj prakash
Ranch Hand

Joined: Oct 30, 2009
Posts: 76
Hi Friends,

can you please explain to me, when to use for-each loop?
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30076
    
149

When you want to loop through something and don't need to change the elements or reference the index.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

Also, when iterating over a Collection and the Iterator isn't needed (for removing elements for instance).


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
surya.raaj prakash
Ranch Hand

Joined: Oct 30, 2009
Posts: 76
Hi Jeanne Boyarsky and Rob Prime,
Thanks for your Reply.

And i have one more doubt, Iterator is just a clutter,what it mean?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

From the Java 5 docs:

So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.


In other words: Use the for-each loop whenever you can; only use the old-style loop when it's really necessary.

You can lookup "clutter" with Google Translate.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

I think they mean that the Iterator is just a temporary thing in most cases. It has exactly one purpose - iterating over the collection. Just like loop counters (i, j, etc) it should only live during the iteration and then be discarded.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37943
    
  22
surya.raaj prakash wrote: . . . Iterator is just a clutter,what it mean?
It means you ought not read the website or book where you found that

And please tell us where you found that, so we can also avoid it
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

It's from the page Jesper linked to - Oracle's own documentation (back then created by Sun).
Gaurav Raje
Ranch Hand

Joined: Jul 23, 2010
Posts: 136
just an addition to what the seniors have mentioned.
When you design a class(in this case a collectioin class). Always assume, that even though you as the creator knows everything in it, its internal semantics, to the outside world, it is just a blob. They have (or should have) accecss only in a way which you want them to. In case of collections, you might have a data structure internally, which holds all elements.
}But if you want people to iterate through them, you should have some mechanism.

Foreach (for is a standardized way of iterating. This way you provide the other classes a way of accessing your elements in an order which you specified.
Unfortunately language semantics mess up the whole system if you edit any object on the way. Hence the read only limitation.

the for each loop follows the order specified by your iterator. So if the iterable(and thus the iterator by the iterator defined here) interface is implemented correctly, it should produce a safe output.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37943
    
  22
Rob Prime wrote:It's from the page Jesper linked to - Oracle's own documentation (back then created by Sun).
No, it isn't. I meant the bit about "iterator is a clutter". There is nothing about clutter in the Java™ Tutorials section.
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

in short.
we can say for-each loop is same as for loop.
In case of for-each loop, we are only reducing for loop and made the compiler to do some intialization and comparion,assignment by itself.
for-each is most likely used with array.see

if we have a array like
int[] a=new int[]{1,2,3,4,5,6,7,8,9,}

in case of for loop we mention it like this.

for(int i=0;i<=a.length;i++);
System.out.println(a[i]);

but by using for-each loop it can simply be represented as.

for(int i:a)
System.out.println(i);


output will be same for both.


SCJP6.0,My blog Ranchers from Delhi
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

Campbell Ritchie wrote:
Rob Prime wrote:It's from the page Jesper linked to - Oracle's own documentation (back then created by Sun).
No, it isn't. I meant the bit about "iterator is a clutter". There is nothing about clutter in the Java™ Tutorials section.

Jesper posted this link. Check out the piece of text just after the first code block.
akash shrimali
Ranch Hand

Joined: Jul 28, 2010
Posts: 45
the for each loop allows you the features of iteration , loop includes all the features of previous for loop but has its own enhancements like printing the No of elements in array , is smaller in size , easy to use , proper definition for the developer !!
Gaurav Raje
Ranch Hand

Joined: Jul 23, 2010
Posts: 136
akash shrimali wrote:the for each loop allows you the features of iteration , loop includes all the features of previous for loop but has its own enhancements like printing the No of elements in array , is smaller in size , easy to use , proper definition for the developer !!


No it doesnt..... it is not designed to modify elements which a for loop is.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37943
    
  22
Rob Prime wrote:Jesper posted this link. Check out the piece of text just after the first code block.
Found it, thank you. It actually says
The for-each construct gets rid of the clutter and the opportunity for error.
. . . which is different from what was originally quoted.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

The three sentences before that are
The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong.

The first of these three is definitely identical to what was quoted before.
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

for each always saves your code for throwning uncessary excepion like ArrayIndexoutOfBound Exception
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

search on google the meaning of clutter(if you donot know that)
and try relate it with iterator
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37943
    
  22
Rob Prime wrote:The three sentences before that are
The iterator is just clutter.
. . .
Even though I used ctrl-F I never found that bit. Sorry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding for-each loop
 
Similar Threads
Using enhanced for loop to iterate in reverse order ?
I/O problem
Help Me Downcast
CSS combined names
printing and returning arrays