Create a ragged/jagged 3d array in java

2k views Asked by At

I want to create a ragged 3d array as followes in java.

Terminology: A 2D array is said to consist of rows and columns. A 3D array is said to consist of slabs, where each slab consists of a 2D array.

The first slab has three rows, the second slab five rows, and the third slab seven rows (i.e., if s denotes the slab, the number of rows in the sth slab is 3+2*s). Within the sth slab, the jth row should have s+j+1 columns

My approach was,

int[][][] mat3d = new int[3][][];
mat3d[0] = new int[3][];
mat3d[0] = new int[5][];

But this gives a compile error. Can anyone please help me to do this. I'm in a real hurry.

1

There are 1 answers

1
Isuru Pathirana On

Error was not due to the code fragment in the question. Compilation failed as the code was not written inside a method. Writing the code with in a method fixes the problem.

public static void main(String args[]){
    int[][][] mat3d = new int[3][][];
    mat3d[0] = new int[3][];
    mat3d[0] = new int[5][];
}

This compiles fine.