Mutating Algorithm - 3 months ago 18

Java Question

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

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

`double[] d = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}`

`matrix[1] = d`

`matrix`

`matrix`

Answer

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.