File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Initialize arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Initialize arrays" Watch "Initialize arrays" New topic

Initialize arrays

Alan Falloon

Joined: Nov 11, 2008
Posts: 2
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

Joined: Nov 20, 2007
Posts: 192
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

Joined: Nov 11, 2008
Posts: 2
thanks a bunch, that problem was really bothering me

it all makes perfect sense now that I Understand how it works
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
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 ]
It is sorta covered in the JavaRanch Style Guide.
subject: Initialize arrays
It's not a secret anymore!