• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

New type of for loop?

 
Tim Manchester
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the explanation & link. I've got it now.

Best Regards,

Tim
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is the new for-loop syntax which was introduced in Java version 5.0:
The For-Each Loop
 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic