Mutating Algorithm Mutating Algorithm - 11 months ago 44
Java Question

Can the size of an N-dimensional array change in Java?

An array in Java is an object. So if I have a 2D array

double[][] matrix = new double[5][5]
then each row of that array is an object referencing a single dimensional array in memory. From my understanding, once the array size is set in java it can not be changed. So let me declare a 1D array
double[] d = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
I am then allowed to set
matrix[1] = d
so that row 1 is now pointing to d in memory. I seems like the array size is not really fixed. I can declare
to be of any size and just change the reference to point to an array of a different size. Why am I allowed to do this if the
size is fixed to be 5 x 5 ?

Answer Source

The assignment

double[][] matrix = new double[5][5];

actually creates 6 array objects. One array whose element type is double[] (i.e. an array of double arrays) having a length of 5 and referenced by the matrix variable, and 5 arrays whose element types are double having a length of 5 and references by matrix[0]...matrix[4].

Just as you can change the matrix variable to refer to a new array by assigning :

matrix = new double[10][10];

you can also change any of the references matrix[i] to refer to a new array by assigning :

matrix[i] = new double[6];

You are not changing any existing array. You are changing the value of a reference variable which referred to one array to refer to a different array.