Java: Jagged Array

By Xah Lee. Date: . Last updated: .

Jagged Array

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 }};.

Array Cannot be Arbitrary Tree

Middle level nodes cannot have different count of elements.

For example, you cannot create a array with a shape like this: { { 3, 4, 5 }, { 77, 50, {1, 2} }}

Java, data structures, array, collection, map