Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Java 2D array not throwing IndexOutOfBoundException?

Tags:

java

arrays

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
}
like image 966
dev Avatar asked Dec 02 '22 12:12

dev


2 Answers

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

like image 139
4castle Avatar answered May 06 '23 14:05

4castle


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.

like image 34
Andreas Avatar answered May 06 '23 14:05

Andreas