Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Why does matrixes accept lines greater than the predefined length?

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?

like image 990
Mr Guliarte Avatar asked Jul 13 '26 21:07

Mr Guliarte


1 Answers

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]
like image 96
Sotirios Delimanolis Avatar answered Jul 16 '26 10:07

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!