Jagged array

When you allocate memory for a multidimensional array, you can allocate the remaining dimensions separately. For example, the following code allocates the second dimension manually.


public class Main {
  public static void main(String[] argv) {
    int twoD[][] = new int[4][];
    twoD[0] = new int[5];
    twoD[1] = new int[5];
    twoD[2] = new int[5];
    twoD[3] = new int[5];
  }
}

When allocating dimensions manually, you do not need to allocate the same number of elements for each dimension.

The following program creates a two-dimensional array in which the sizes of the second dimension are unequal.


public class Main {
  public static void main(String args[]) {
    int twoD[][] = new int[4][];
    twoD[0] = new int[1];
    twoD[1] = new int[2];
    twoD[2] = new int[3];
    twoD[3] = new int[4];

    for (int i = 0; i < 4; i++){
      for (int j = 0; j < i + 1; j++) {
        twoD[i][j] = i + j;
      }
    }
    for (int i = 0; i < 4; i++) {
      for (int j = 0; j < i + 1; j++)
        System.out.print(twoD[i][j] + " ");
      System.out.println();
    }
  }
} 

This program generates the following output:


0 
1 2 
2 3 4 
3 4 5 6 

The array created by this program looks like this:


    [0][0]
    [1][0] [1][1]
    [2][0] [2][1] [2][2]
    [3][0] [3][1] [3][2] [3][3]
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.