This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Problem with enhanced for loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with enhanced for loop" Watch "Problem with enhanced for loop" New topic
Author

Problem with enhanced for loop

MrKamal Joshi
Greenhorn

Joined: Jul 31, 2011
Posts: 24

I tried to populate array by using for each loop but it's not working
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 44031
    
  33
It never does. You should regard elements in the for-each loop s "read only." The for-each loop makes a copy of each element in the array or Iterable<T> and you can assign to that copy, but the assignment is not copied back to the original array or Iterable<T>.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 20080
    
  30

Whenever you need to assign to the current array index while looping, the for-each loop is useless. The old way of looping is the only way to go. Likewise for looping over collections where you possibly need to remove elements, you'll need an explicit Iterator to call its remove() method.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with enhanced for loop
 
jQuery in Action, 3rd edition