Multidimensional arrays allow the organization of data into multiple dimensions, a common example being a two-dimensional array often used to represent tables or matrices. Java provides syntax for the seamless creation of two-dimensional arrays, which this article delves into.
Consider the code snippet:
int[][] multD = new int[5][]; multD[0] = new int[10];
The intent may be to establish a two-dimensional array containing 5 rows and 10 columns, however, this approach encounters syntactic irregularities. To correctly instantiate a two-dimensional array with these dimensions, the following syntax should be employed:
int[][] multi = new int[5][10];
The provided construct serves as a concise representation that equates to the explicit definition:
int[][] multi = new int[5][]; multi[0] = new int[10]; multi[1] = new int[10]; multi[2] = new int[10]; multi[3] = new int[10]; multi[4] = new int[10];
It is imperative to remember that each element within the array is initialized to the default integer value, which is 0. This implies that the above definitions are equivalent to:
int[][] multi = new int[][] { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
This can be further abbreviated to:
int[][] multi = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
The above is the detailed content of How Do I Properly Initialize a Two-Dimensional Array in Java?. For more information, please follow other related articles on the PHP Chinese website!