• Post Reply Bookmark Topic Watch Topic
  • New Topic

i cant understand this code..  RSS feed

 
alex lotel
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

i know that its some kind of new for loop
but it makes no sense to me
 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The new "for-each" loop that came out with Java version 5.0 is new.

The new for-each loop is still used with the "for" keyword, so as not to introduce a new keyword which could cause backward-compatibility problems.

The for-each loop can be used to iterate over an array or over a class that implements the Iterable interface.

In the following loop, a variable "o" of type "Object" is declared to iterate over the contents of "ms". Inside the for loop, you can use the variable "o" each time through the loop. It will contain each successive value of ms.

for (Object o : ms) {

}

Tutorial on the new for-each loop in java 5.0
[ March 17, 2008: Message edited by: Kaydell Leavitt ]
 
alex lotel
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so each time it encounter the value of O in ms
it executes the inside of the for
??
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First let me point out that in order to implement the Iterable interface you must provide a method called iterator(), not iterate().

so each time it encounter the value of O in ms
it executes the inside of the for
??


Not quite, it takes each object that the Iterator.next() method returns and assigns it to the Object reference o, it is then avaiable for use in the code block. The code in your post is shorthand for:

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!