This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes New type of for loop? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "New type of for loop?" Watch "New type of for loop?" New topic
Author

New type of for loop?

Tim Manchester
Ranch Hand

Joined: Nov 03, 2004
Posts: 62
Howdy,

I was perusing some code and I saw a for loop written in a way that I've never seen before. I was wondering if someone could explain this to me:

for (TransferLimit transferLimit : transferLimits)

This is not the typical for syntax that I'm used to. What is this?

Regards,

Tim
vatsalya rao
Ranch Hand

Joined: Feb 14, 2007
Posts: 63
in this the variable "transferlimit"holds the values from th evariable "transferlimits"which are of type "Tranferlimit" .me too camt to know this recently from SUN site you too can refer to it from "http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html"
regards,
Tim Manchester
Ranch Hand

Joined: Nov 03, 2004
Posts: 62
Thanks for the explanation & link. I've got it now.

Best Regards,

Tim
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14117
    
  16

It is the new for-loop syntax which was introduced in Java version 5.0:
The For-Each Loop


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
gaurav abbi
Ranch Hand

Joined: Jan 05, 2007
Posts: 108
hi all,
i went to the link where explanation is given for using such kind of for syntax, there its also said,
"The for statement also has another form designed for iteration through Collections and arrays"

i'm not able to figure out how the loop will be used in case os collections for iteration, because normally wht we do is smthng like this

Iterator itr = list.iterator();

while(itr.hasNext()){
itr.next()
------
-----
}

any code snippet about the new "for" syntax for using with collections
and why it should be preferred over current way of iteration.

thanks in advance.


thanks,<br />gaurav abbi
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
The new for syntax will automatically create an iterator for you.

However, using the new for syntax you will not be able to remove elements from the Collection. Also you will not be able to do anything that requires direct access to the iterator.

An example would be



The new for each loop makes the code more concise.
 
 
subject: New type of for loop?