When creating a 2D array, how does one remember whether rows or columns are specified first?
On the exam assume that any 2 dimensional (2D) array is in row-major order. The outer array can be thought of as the rows and the inner arrays the columns. On the exam all inner arrays will have the same length even though it is possible in Java to have inner arrays of different lengths (also called ragged arrays).
In the standard mathematical notation used for linear algebra, the first dimension of an array (or matrix) is the row, and the second dimension is the column.
Note: When you initialize a 2D array, you must always specify the first dimension(no. of rows), but providing the second dimension(no. of columns) may be omitted.
In a 2D array, a cell has two indexes one is its row number, and the other is its column number. Sorting is a technique for arranging elements in a 2D array in a specific order. The 2D array can be sorted in either ascending or descending order.
Java specifies arrays similar to that of a "row major" configuration, meaning that it indexes rows first. This is because a 2D array is an "array of arrays".
For example:
int[ ][ ] a = new int[2][4]; // Two rows and four columns. a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3]
It can also be visualized more like this:
a[0] -> [0] [1] [2] [3] a[1] -> [0] [1] [2] [3]
The second illustration shows the "array of arrays" aspect. The first array contains {a[0] and a[1]}
, and each of those is an array containing four elements, {[0][1][2][3]}
.
TL;DR summary:
Array[number of arrays][how many elements in each of those arrays]
For more explanations, see also Arrays - 2-dimensional.
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