Why doesn't this Java 2D array throw an IndexOutOfBoundException?

I initialize the 2D array by specifying both the number of rows and columns. I expected it to throw an error if I put in more elements than the number declared during 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
}
+4
source share
5 answers

According to the Java language specification, ยง15.10.2. Estimating the creation time of expressions for creating arrays , Example 15.10.2-2. Creating a multidimensional array :

Announcement:

float[][] matrix = new float[3][3];

equivalent to behavior:

float[][] matrix = new float[3][];
for (int d = 0; d < matrix.length; d++)
    matrix[d] = new float[3];

That means your code:

int[][] arr = new int[2][2];
arr[0] = new int[]{1,2};
arr[1] = new int[]{3,4,5};

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};

, , 2D-.

, , :

int[][] arr = new int[2][];
arr[0] = new int[]{1,2};
arr[1] = new int[]{3,4,5};

, GC, .

+4

Java 2D- , . . .

int[][] arr = new int[2][2];:

int[][] arr = new int[2][];
arr[0] = new int[2];
arr[1] = new int[2];

arr[1] int[], . Java , .

- 15.10.2-2.

+10

new int[]{3,4,5} new. 3.

int[1][2] = 5, IndexOutOfBoundsException, .

. " 2D-" .

+2

, java . Java . new int[2][2] . , "", . arr[1] = new int[]{3,4,5}; , (, ) Java. , , :

int[][] arr = new int[2][2];
arr[1][0] = 3;
arr[1][1] = 4;
arr[1][2] = 5; # throws ArrayIndexOutOfBoundsException
+1
source

You create a new line. If you are debugging your code, you will see that after arr[1] = new int[]{3,4,5};now you have this

enter image description here

if you do this instead:

 int[][] arr = new int[2][2];
 arr[1][3] = 1;

you will get your ArrayIndexOutOfBoundsException

0
source

Source: https://habr.com/ru/post/1682781/


All Articles