Java: Jagged Arrays

By Xah Lee. Date: . Last updated: .

You can create a 2D array with m rows and each row have different number of slots.

public class Aj {
    public static void main(String[] args) {

        int[][] xx = { { 3, 4, 5 }, { 77, 50 }};

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

// prints
// 3 4 5
// 77 50

Normally, array creation takes 3 steps in java:

There's a irregular syntax that does all the above steps in one, like this: int[][] xx = { { 3, 4, 5 }, { 77, 50 }};.

Note: even though the leafs of a array can be jagged, but not any middle level nodes. So, arbitrary tree cannot be created as array. For example, you cannot create a array with a shape like this: { { 3, 4, 5 }, { 77, 50, {1, 2} }}