HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Java Tutorial: Jagged Arrays

Advertise Here For Profit

Xah Lee, 2005-02

A n-dimentional 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} }}”

Arrays Of Objects

You can make a array of Objects in Java. Here is a example.

class H {
    int x;
    H (int n) {x=n;}
}

public class ar4 {
    public static void main(String[] args) {
        H[] myA;
        myA = new H[4];

        for (int i = 0; i < myA.length; i++) {
            myA[i] = new H(i);
            System.out.print(new Integer(myA[i].x) +" ");
        }
    }
}

Note that in the code H[] myA, declares that the variable myA is a datatype of array of H. The line myA = new H[4]; assigns this variable myA, a thing, that is a array of 4 elements, and each element is of type H.

The line myA[i] = new H(i); sets the value for each slot of myA. And, that value being the instantiation of H with i as the init parameter to the constructor of H.

2005-02

Although java allows this convenience for array type declaration & assignment and capacity declaration & slots fulfillment in one shot: int[] v= {3,4};

However, this syntactical idiosyncracy cannot be used generally. For example, the following is a syntax error:

 int[] v= new int[2];
 …
 v= {i,j};

Full test code below:

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”.

See also: arrays; rectancular array

blog comments powered by Disqus