One final example on this important issue. This time Java1513.java, in figure 15.15, starts with three one-dimensional arrays, which then are used to create a two-dimensional array. And with this program example we can now move on. Figure 15.15 // Java1513.java // In this program 1D arrays are created first and then used to create a 2D array. public class Java1513 { public static void main(String[ ] args) { int[ ] list1 = {1,2,3}; int[ ] list2 = {4,5,6}; int[ ] list3 = {7,8,9}; int[ ][ ] mat = new int[3][3]; mat[0] = list1; mat[1] = list2; mat[2] = list3; displayMatrix(mat); } public static void displayMatrix(int[ ][ ] m) { for (int r = 0; r < m.length; r++) { for (int c = 0; c < m.length; c++) System.out.print(m[r][c] + " "); System.out.println(); } } } 15.5 Two-Dimensional Dynamic Arrays The ArrayList class is a very practical one-dimensional, dynamic array with many convenient methods. It is rare to see this class used for two-dimensional arrays and the static 2D array is much easier to declare and manipulate. Yet it is possible to create a two dimensional, dynamic array with the ArrayList class, as shown in figure 15.16 with program Java1514.java. Pay particular attention to the syntax of the nested generics declaration.
One final example on this important issue. This time Java1513.java, in figure 15.15, starts with three one-dimensional arrays, which then are used to create a two-dimensional array. And with this program example we can now move on. Figure 15.15 // Java1513.java // In this program 1D arrays are created first and then used to create a 2D array. public class Java1513 { public static void main(String[ ] args) { int[ ] list1 = {1,2,3}; int[ ] list2 = {4,5,6}; int[ ] list3 = {7,8,9}; int[ ][ ] mat = new int[3][3]; mat[0] = list1; mat[1] = list2; mat[2] = list3; displayMatrix(mat); } public static void displayMatrix(int[ ][ ] m) { for (int r = 0; r < m.length; r++) { for (int c = 0; c < m.length; c++) System.out.print(m[r][c] + " "); System.out.println(); } } } 15.5 Two-Dimensional Dynamic Arrays The ArrayList class is a very practical one-dimensional, dynamic array with many convenient methods. It is rare to see this class used for two-dimensional arrays and the static 2D array is much easier to declare and manipulate. Yet it is possible to create a two dimensional, dynamic array with the ArrayList class, as shown in figure 15.16 with program Java1514.java. Pay particular attention to the syntax of the nested generics declaration.
Text15-Two-DimensionalArray.docx