Java Tutorial: Jagged Arrays

, , …,

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[][] myA = { { 3, 4, 5 }, { 77, 50 }};

        for (int i = 0; i < myA.length; i++) {
            for (int j = 0; j < myA[i].length; j++) {
                System.out.print(myA[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[][] myA = { { 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} }}

blog comments powered by Disqus