How are two-dimensional arrays arranged in Java?
In Java, a two-dimensional array is a data structure made up of multiple one-dimensional arrays, which can be viewed as a table. The arrangement of a two-dimensional array is based on row and column indices.
There are two ways to arrange a two-dimensional array:
- Row-major order: arrange in the order of the rows. For example, for a 3-row, 4-column 2D array, the order would be: (0,0), (0,1), (0,2), (0,3), (1,0), (1,1), (1,2), (1,3), (2,0), (2,1), (2,2), (2,3).
- Columns are prioritized in the ordering: meaning they are arranged in the order of columns. For example, for a 3×4 two-dimensional array, the ordering would be: (0,0), (1,0), (2,0), (0,1), (1,1), (2,1), (0,2), (1,2), (2,2), (0,3), (1,3), (2,3).
In Java, you can use nested for loops to access and manipulate elements in a 2D array. For example, for a 3×4 array named ‘arr’, you can use the following code to traverse and output the elements in row-major order.
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
Similarly, to traverse and output the elements of a two-dimensional array in column-major order, you can exchange the nested loop order.
for (int j = 0; j < arr[0].length; j++) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
In the code above, arr is a two-dimensional array. The first loop iterates through the rows, and the second loop iterates through the columns, allowing access to the element in the i-th row and j-th column using arr[i][j].