• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with enhanced for loop

 
MrKamal Joshi
Greenhorn
Posts: 24
Java
  • 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
Posts: 48374
56
  • Likes 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: 20492
54
Chrome Eclipse IDE Java Windows
  • Likes 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic