I am initializing a 2D array, specifying both number of rows and columns. I expected it to throw an error if I insert more items than the number declared in initialization, but the code works fine.
static void arrayChecks(){
int[][] arr = new int[2][2];
arr[0] = new int[]{1,2};
arr[1] = new int[]{3,4,5}; //adding 3 items to a 2-column row. No exception thrown
//arr[2] = new int[]{6,7}; //throws ArrayIndexOutOfBoundsException as expected.
for(int[] a : arr){
for(int i : a){
System.out.print(String.valueOf(i));
}
}
//output = 12345
}
Java doesn't support 2D arrays in the way some languages do. It just treats them as an array of array references. These inner arrays can be reassigned to another array of any length.
The desugared version of int[][] arr = new int[2][2];
is:
int[][] arr = new int[2][];
arr[0] = new int[2];
arr[1] = new int[2];
You can reassign arr[1]
to any int[]
that you want. Java allows for jagged arrays, where each inner array is a different length.
Reference - Example 15.10.2-2. Multi-Dimensional Array Creation
According to Java Language Specification, §15.10.2. Run-Time Evaluation of Array Creation Expressions, Example 15.10.2-2. Multi-Dimensional Array Creation:
The declaration:
float[][] matrix = new float[3][3];
is equivalent in behavior to:
float[][] matrix = new float[3][]; for (int d = 0; d < matrix.length; d++) matrix[d] = new float[3];
This means that your code:
int[][] arr = new int[2][2];
arr[0] = new int[]{1,2};
arr[1] = new int[]{3,4,5};
Is the same as:
int[][] arr = new int[2][];
for (int d = 0; d < arr.length; d++)
arr[d] = new int[2];
arr[0] = new int[]{1,2};
arr[1] = new int[]{3,4,5};
Or:
int[][] arr = new int[2][];
arr[0] = new int[2];
arr[1] = new int[2];
arr[0] = new int[]{1,2};
arr[1] = new int[]{3,4,5};
As you can see, the last two statements replace the references to the two subarrays created by the 2D array creation expression.
This means that the result is exactly the same as:
int[][] arr = new int[2][];
arr[0] = new int[]{1,2};
arr[1] = new int[]{3,4,5};
Except that you wasted time and GC creating the two subarrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With