Meaningless Drivel is fun!
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 Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with enhanced for loop" Watch "Problem with enhanced for loop" New topic

Problem with enhanced for loop

MrKamal Joshi

Joined: Jul 31, 2011
Posts: 24

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

Joined: Oct 13, 2005
Posts: 41091
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

Joined: Oct 27, 2005
Posts: 19908

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.

How To Ask Questions How To Answer Questions
It is sorta covered in the JavaRanch Style Guide.
subject: Problem with enhanced for loop