File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with enhanced for loop

 
MrKamal Joshi
Greenhorn
Posts: 24
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried to populate array by using for each loop but it's not working
 
Campbell Ritchie
Sheriff
Pie
Posts: 47244
52
  • 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic