Multidimensional Arrays

In Java, multidimensional arrays are actually arrays of arrays. For example, the following declares a two-dimensional array variable called twoD.


int twoD[][] = new int[4][5];

This allocates a 4-by-5 array and assigns it to twoD. This array will look like the one shown in the following:


   [leftIndex][rightIndex]       


   [0][0] [0][1] [0][2] [0][3] [0][4] 
   [1][0] [1][1] [1][2] [1][3] [1][4] 
   [2][0] [2][1] [2][2] [2][3] [2][4] 
   [3][0] [3][1] [3][2] [3][3] [3][4]
The wrong way to think about multi-dimension arrays

+----+----+----+
|   1|   2|   3|
+----+----+----+
|   4|   5|   6|
+----+----+----+
|   7|   8|   9|
+----+----+----+
right way to think about multi-dimension arrays

+--+        +----+----+----+
|  |--------|   1|   2|   3|
+--+        +----+----+----+     +----+----+----+
|  |-----------------------------|   4|   5|   6|
+--+   +----+----+----+          +----+----+----+
|  |---|   7|   8|   9|
+--+   +----+----+----+
An irregular multi-dimension array

+--+        +----+----+
|  |--------|   1|   2|
+--+        +----+----+          +----+----+----+
|  |-----------------------------|   4|   5|   6|
+--+   +----+----+----+----+     +----+----+----+
|  |---|   7|   8|   9|  10|
+--+   +----+----+----+----+

The following code use nested for loop to assign values to a two-dimensional array.


public class Main {
  public static void main(String args[]) {
    int twoD[][] = new int[4][5];
    for (int i = 0; i < 4; i++) {
      for (int j = 0; j < 5; j++) {
        twoD[i][j] = i*j;
      }
    }
    for (int i = 0; i < 4; i++) {
      for (int j = 0; j < 5; j++) {
        System.out.print(twoD[i][j] + " ");
      }
      System.out.println();
    }
  }
}
  

This program generates the following output:


0 0 0 0 0 
0 1 2 3 4 
0 2 4 6 8 
0 3 6 9 12 

Three-dimensional array

The following program creates a 3 by 4 by 5, three-dimensional array.


public class Main {
  public static void main(String args[]) {
    int threeD[][][] = new int[3][4][5];

    for (int i = 0; i < 3; i++)
      for (int j = 0; j < 4; j++)
        for (int k = 0; k < 5; k++)
          threeD[i][j][k] = i * j * k;

    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 4; j++) {
        for (int k = 0; k < 5; k++)
          System.out.print(threeD[i][j][k] + " ");
        System.out.println();
      }
      System.out.println();
    }
  }
}


This program generates the following output:


0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 

0 0 0 0 0 
0 1 2 3 4 
0 2 4 6 8 
0 3 6 9 12 

0 0 0 0 0 
0 2 4 6 8 
0 4 8 12 16 
0 6 12 18 24 
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.