Java Tutorial: Jagged Arrays

, ,

A n-dimensional array in java needs not be rectangular. For example, normally a 2D array can be thought of as a matrix of m rows and n columns; any row has same number of slots as any other row. However, in Java you could create a 2D array with m rows and each row have different number of slots.

Here is a example.

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

        int[][] myA = { { 3, 4, 5 }, { 77, 50 }};
        // special syntaxt to create jagged array in one shot.

        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();
        }
    }
}

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

Java Ugliness: Syntactic Irregularity and Ad Hoc Logic

In this irregular but convenient syntax: int[] v = {3,4};, it does several things in one shot: {array type declaration, value assignment, number of elements declaration, slots fulfillment}. However, this syntactical idiosyncrasy cannot be used generally. For example, the following is a syntax error:

 int[] v = new int[2];
 v = {3, 4};

Here's a complete code you can try.

public class H {
    public static void main(String[] args) {
        int[] v = new int[2];
        v = {3,4};
        System.out.print(v[0]);
    }
}

The compiler error is: “illegal start of expression”.

blog comments powered by Disqus