• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initialize arrays

 
Alan Falloon
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a 3 dimensional array 'readings' which holds months, days and hours.
I want to initialize every element in the array to hold the same value, lets say 6.


this compiles but when I inspect the object it shows me that every element is still 'null'


Any thoughts as to why this isn't working as 'hour' is pointing to a specific element but it doesn't change the value? Or is there simply an easyer way to initialize multi-dimensional arrays?
 
Taariq San
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The trouble with that Alan, is that the double hour is assigned the value found in the array, then it is assigned the value 6;
That doesn't get slapped back into the array.

I'll change the inner for loop to the old for loop so it's clearer what's going on, indeed you'll need the old style to make the assignment.

 
Alan Falloon
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a bunch, that problem was really bothering me

it all makes perfect sense now that I Understand how it works
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

There is a not-well-known problem with the for-each (enhanced for) loop: an assignment in the loop like that doesn't seem to work. You have to regard the for-each loop as "read only." You don't get any compiler warnings nor exceptions, which I find annoying. It isn't in the Java� Tutorials, but it's in Deitel and Deitel (6th edition page 303)
Note, however, that the enhanced for statement can be used only to access array elements-it cannot be used to modify elements.
Horstmann and Cornell (7th edition vol I page 82) says
The enhanced for loop . . . sets the given variable to each elements of the collection and then executes the statement (which, of course, may be a block).
That suggests you might get a copy reference; if you change that you don't change the original array/collection.
[ November 12, 2008: Message edited by: Campbell Ritchie ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic