Site Search:

Declare, instantiate, initialize and use multi-dimensional array

Back OCAJP

In Declare, instantiate, initialize and use a one-dimensional array, we learned that array is an ordered list of objects or primitives.

This concept can go one step farther, the objects stored in an array can be type of array.


For example int [2] [5] twoD; declares a matrix-like 2-D array named twoD. The first dimension have 2 elements. Each element have type int array, which is an object reference variable pointing to an int [5] array object.

int [3][2][5] threeD; declares a cubic-like 3-D array named threeD. The first dimension have 3 elements. Each element have type int array, which is an object reference variable pointing to an int[2][5] array object.

multi-dimensional array don't have to be square-shape or cubic-shape, the array elements can have different length.
int[][] juggle = new int[][]{{1,2},{3},{1,1,1,1}}; declares a 2-D array named juggle. The first dimension have 3 elements. Each element have type int array. The first element refers to an int[2] array, the second element refers to an int[1] array, the third one refers to an int[4] array.



OCAJP>cat test.java 
import java.util.*;
class test {
  public static void main(String... args) {
    //int[][] a = new int[][]; //missing first dimension
    //int[][] a = new int[];  //1D can not be assigned to 2D
    int[][] twoD = new int[][]{{1,1,1},{2,2},{},{1,9,0,8}};
    //int[2][3] twoD = new int[][]{{1,1,1},{2,2,2}};  //not compile
    for(int[] i: twoD) {
      //for(int j: i) System.out.print(i[j]+" ");  //java.lang.ArrayIndexOutOfBoundsException: 2
      //System.out.println();
    } 
    
    for(int i=0; i< twoD.length; i++) {
      for(int j=0; j< twoD[i].length; j++) {
        System.out.print(twoD[i][j] + " ");
      }
      System.out.println();
    }
    
    int twoD2 [][] = new int[][]{{1,2},{0,0}}, maxi, maxj, maxk, max;
    int [] twoD3[] = new int[][]{{1,2,3}};
    int[][][] threeD = {twoD,twoD2,{{1,3},{10, 0, 1, 2, 5}},twoD3,{}};
    threeD[2][1][0] = 1000;
    maxi = (maxj = (maxk = 0));
    for(int i = 0; i< threeD.length; i++) {
      for(int j = 0; j < threeD[i].length; j++) {
        for(int k = 0; k < threeD[i][j].length; k++){
          if(threeD[i][j][k] > threeD[maxi][maxj][maxk]) {maxi = i; maxj = j; maxk =k;}
        }
      }
    }
    System.out.println("the max value is at ["+ maxi + "," +maxj + "," + maxk + "] :" + threeD[maxi][maxj][maxk]);
    for(int i: threeD[maxi][maxj]) System.out.print(i + " "); 
    System.out.println();
  }
}
OCAJP>javac test.java 
OCAJP>java test
1 1 1 
2 2 

1 9 0 8 
the max value is at [2,1,0] :1000
1000 0 1 2 5 
Back OCAJP