| Author |
MultiDimensional Arrays
|
Lucky J Verma
Ranch Hand
Joined: Apr 11, 2007
Posts: 277
|
|
I read in some Java material, MultiDimensional arrays in Java are implemented as array of arrays ie each row is a separate array. When we define as array say , 2 x 3 array int arr[][]={{1,2,3}, {3,4,5}}; i read ,multiple objects are created ,its not one object. so according to my understanding , 2+1=3 objects shud be created,2for each row, 1 for storing index to 2 rows. But ,in this website http://www.go4expert.com/forums/showthread.php?t=1162 some other way to count objects is given. i want to know what is true. thnx
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Note: This post is in response to another response that has since been deleted (so it might seem a little out of context). There are 3 array objects... (2*3 = 6 gives the total number of elements -- which, in this case, are primitive ints.) [ April 12, 2007: Message edited by: marc weber ]
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
That webpage has an error. The explanation seems correct, but the total is wrong. Where it says...
int[][] a2 = new int[10][5]; ... This actually allocates 6 objects: a one-dimensional array of 5 elements for each of the rows, and a one-dimensional array of ten elements, with each element pointing to the appropriate row array.
...it should say something like...
This actually allocates 11 objects: a one-dimensional array of 5 elements (the ints) for each of the ten rows (so that's ten one-dimensional arrays, each containing 5 ints); and a one-dimensional array of ten elements, with each element pointing to the appropriate row array.
This can be demonstrated with the following code. It creates an int[10][5], then iterates through to print each element. The ints print as default zeros. The array objects print as [I@xxxxxx, where "[I" indicates an int array, and "xxxxxx" represents the memory address. You will see from the output that there are 11 array objects.
|
 |
 |
|
|
subject: MultiDimensional Arrays
|
|
|