• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Assign 2D jagged array values using for-each loop (Enhanced for Loop)

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have managed to assign value using regular for loop. I wondered if its possible to do the same using for-each loop? I tried various ways and none of it worked.

Its just for learning purpose.


 
Marshal
Posts: 76862
366
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

joebloggs Bloggs wrote:. . . . I wondered if its possible to do the same using for-each loop? . . .

Depends how brave you are feeling.

The very simple answer is, you can't.

The simple answer is that a for‑each loop looks on the array as read‑only and you cannot therefore assign to any of the array's elements.

The difficult answer is that the JLS (=Java® Language Specification) tells you that the elements in the array being iterated are copied into a variable local to the loop. If you try to reassign anything, you are simply assigning to that local variable.. You can only gain access to an array element with array[i]. Assignments to the local copy are not reflected in the backing array. The #a and #i variables in the JLS section are only to be seen on the right of an assignment operator, and cannot be put to the left of it where they could be assigned to.
 
Your mother is a hamster and your father smells of tiny ads!
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic