This is copied directly from the book so disregard all of the comments and extraneous info. My question is how is this a 2 dimensional array? I define it as such, but the output of the length of the array is 3, and with the element of the second line 4, I don't see how that could make it 2 dimensions. What does the dimension refer to? I understand it's not a square matrix, but if I were to try to imagine it as a matrix, what would it look like? Sorry re: long post.
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
posted
0
Its an array of int arrays. In Java, thats what all *multi-dimensional* arrays are. They are just arrays of arrays. So its best to the reference to "myarray" as a reference to a single dimensional array of length 3, the element at index 0 (myarray[0]) is a reference to an int[] of length 2, the element at index 1 (myarray[1]) is a reference to an int[] of length 4 and so on. So myArray[x][y] refers to the yth element of the xth array of myArray[][].
In some other languages, you had true multi-dimensional arrays. you would get one big block of contiguous memory, and the indicies could be used to calculate exactly where in the block a specific element would be. I believe that the elements were really stored in that chunk.
Java is different. An array is really nothing more that a list of (basically) addresses telling you where the element REALLY is in the heap. When you define an array, what you are REALLY doing is saying "each element in this array will hold the address of THIS kind of thing". That's why your "System.out.println("myarray.length = " + myarray.length);" prints 3 - your array holds 3 things.
Now, what those three things happen to be are... arrays. You can get the length of each of those 'sub-array' (that's my term, not an official java term). It doesn't really make a lot of sense to ask "what are the 2 dimensions of myarray, since each of the 3 sub-arrays are a different length.
Never ascribe to malice that which can be adequately explained by stupidity.
Jake Miller
Ranch Hand
Joined: Jun 27, 2007
Posts: 43
posted
0
Awesome, thanks, that does help. I don't know why I was having so much trouble grasping that concept. For some reason I was convincing myself that 2-d meant it was only 2 elements long, completely wrong. Thanks all!
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
0
In some other languages, you had true multi-dimensional arrays. you would get one big block of contiguous memory, and the indicies could be used to calculate exactly where in the block a specific element would be. I believe that the elements were really stored in that chunk.
Now I'll have nightmares about reading COBOL dumps.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi