Multi-dimensional arrays
| Code | Result |
|---|---|
// Allocation final int[][] MATRIX = new int[2][3]; // Initialization for (int row = 0; row < 2; row++) { for (int col = 0; col < 3; col++) { MATRIX[row][col] = col + row; } } // Output for (int row = 0; row < 2; row++) { System.out.println(Arrays.toString(MATRIX[row])); } |
[0, 1, 2] [1, 2, 3] |
final int[][] MATRIX = new int[2][]; // Array containing two int arrays
MATRIX[0] = new int[3]; // first int array
MATRIX[1] = new int[3]; // second int arrayConclusions:
-
Java only supports one-dimensional arrays.
-
By means of nesting we get the illusion of multi- dimensional arrays.
No. 155
2-dimensional arrays and .length
|
Q: |
|
||||||
|
A: |
Two-dimensional arrays in Java™ are nested arrays of arrays. We thus choose appropriate data types: // Allocation final int[][] MATRIX = new int[2][3]; // Initialization for (int row = 0; row < MATRIX ❶; row++) { for (int col = 0; col < MATRIX[row].length ❷; col++) { MATRIX[row][col] = col + row; } } // Output for (final int[] ❸ row : MATRIX) { System.out.println(Arrays.toString(row)); }
|
final int[][] MATRIX = new int[][] {
{0, 1, 2},
{1, 2, 3}
};| Code | Result |
|---|---|
|
[Jill, Tom] [Jane, Smith, Joe] [Jeff] |
No. 156
Representing revenues by quarter and department
|
Q: |
A CEO requires quarterly revenue reports for each of the company's three departments: | Q1 Q2 Q3 Q4 -------------+------------------------ Department 1:| 17255 33198 32112 40213 Department 2:| 7629 13221 9226 10231 Department 3:| 34198 71926 25981 38912 Create a corresponding TipIf you actually favour colors like the above red text, you may want to read How to print color in console using System.out.println?. |
|
A: |
|
