Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

for(int i:objList) i don understand how this works?  RSS feed

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
in our project in many places they have used for loops like -



where objList is an List. I havent been able to understand how this is implemented as I somehow prefer using the traditional "for" loop. So can someone please throw some light on this enhanced for loop as they call it.
 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

***now first time the first object of objList is assigned to i (autoboxing is done) i=4 , then i=6..till end
 
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More information on the enhanced for loop can be found here http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html
 
Sheriff
Posts: 21745
102
Chrome Eclipse IDE Java Spring Ubuntu VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The above is shorthand for the following:
For arrays it is similar:
Now in your example, objList is probably a List<Integer>, which means that besides this for-each loop, it is also using auto unboxing to convert Integer objects into ints implicitly.
 
Rancher
Posts: 1369
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This construct was added to the language to make iterating through collections less uglier or more readable. You can use it to iterate over both a collection and an array(as already demonstrated in earlier posts).

Assuming you know how to use a for loop, if you find this new syntax confusing, try reading it as:
"for each integer i in the objList array or iterable do the following.."



 
Don't touch me. And dont' touch this tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!