For instance:
int[][] matrix = new int[3][1];
int[] vector = {1,2,3,4,5};
matrix[0] = vector;
It compiles and runs normally, even though vector
has a greater length than a line of matrix
would stand for.
Why does Java accept this?
This
int[][] matrix = new int[3][1];
Defines an array of int
arrays. Specifically, it defines an array of size 3
. Each of those three elements is then initialized with a reference to a new array of size one, where that element is initialized with the value 0.
When you then do
matrix[0] = vector;
You are assigning a copy of the reference value stored in vector
(which references an int[]
with 5 elements) to the element at index 0 in matrix
.
Because drawings are fun:
int[][] matrix = new int[3][1];
can be illustrated as
0x0001 -> int[][] of size 3, elements = [0x0123, 0x0456, 0x0789]
[address]
0x0123 -> int[] of size 1, elements = [0]
0x0456 -> int[] of size 1, elements = [0]
0x0789 -> int[] of size 1, elements = [0]
matrix = 0x0001
where 0x0001
, 0x0123
, 0x0456
, and 0x0789
are examples of reference values (think of it as an address to an object).
This
int[] vector = {1,2,3,4,5};
adds a new int[]
0x9999 -> int[] of size 7, elements = [1,2,3,4,5]
vector = 0x9999
and
matrix[0] = vector;
makes it
0x0001 -> int[][] of size 3, elements = [0x9999, 0x0456, 0x0789]