Mutating Algorithm
Mutating Algorithm

Reputation: 2758

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 matrix 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 matrix size is fixed to be 5 x 5 ?

Upvotes: 3

Views: 60

Answers (2)

GhostCat
GhostCat

Reputation: 140457

Simply spoken: because that is how the fathers of Java made arrays work.

And the syntax gives a hint there:

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

You see, the 5,5 only shows up on the right hand side! Meaning: the array dimensions are not part of "type" of matrix!

The key thing is: there are no true "multi dimensional" arrays in Java. There is no way to say: this thing should be "5 x 5". You always end up with an array of "rows"; and each row contains an array of columns. And therefore, those columns can have different lengths,as they are completely independent of each other!

Upvotes: 3

Eran
Eran

Reputation: 393846

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.

Upvotes: 5

Related Questions