Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

for-each version for  RSS feed

 
natt walters
Greenhorn
Posts: 17
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the iteration variable declared in the for-each version for loop is read only and contains the elements of the collection, how can it act as an index as well to terminate the loop early when intended to. Like in




Can anybody please explain this.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable declared in the enhanced for-loop can not be used as an index. If you want to have an index then use the normal for-loop or declare a variable before the for-loop and increment it on each loop.
 
natt walters
Greenhorn
Posts: 17
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you but how does the statement
if(x==5)break;
work. The variable x which is the iteration variable of enhanced for loop which is intended to hold elements of collection respond to index 5 of the collection nums as in the code.
 
natt walters
Greenhorn
Posts: 17
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output if this fragment of code is explained to cause a break in the enhanced for loop when it encounters the statement if(x==5)break; resulting the sum of first five elements of the collection. If this is the case then five the index number is assigned to x making it to act as an index.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It breaks out of the for loop as soon as it finds an element in the array that has the value 5 - not when it reaches the 5th element in the array.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:It breaks out of the for loop as soon as it finds an element in the array that has the value 5 - not when it reaches the 5th element in the array.

And it's just a coincidence that these happen to both be true because of the definition of nums[].
 
natt walters
Greenhorn
Posts: 17
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for clearing my doubt.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!