Home > Mobile >  3D arrays in JAVA with different number of elements
3D arrays in JAVA with different number of elements

Time:11-03

how to make this kind of array (different number of elements in each parent array) if i want to take the number of elements from the user :

int[][][] test = {
            {
              {0, 0, 0}, 
              {0, 0, 0}
            }, 
            { 
              {0, 0, 0, 0}, 
              {0, 0, 0, 0}, 
              {0, 0, 0, 0}
            } 
        };

CodePudding user response:

What you're describing is called a jagged array, an array whose elements are arrays of unequal lengths. You can prompt the user for inputs, then use those inputs to initialize your jagged array:

int size;
int myArray[][][];
Scanner s = new Scanner();

// Initialize outer array
System.out.println("How many elements in myArray?");
size = s.nextInt();
myArray = new int[size][][];

// Initialize each inner array
for (int i = 0; i < myArray.length; i  ) {
     System.out.println("How many elements in myArray["   i   "]?");
     size = s.nextInt();
     myArray[i] = new int[size][];
     
     // For each inner array, initialize each inner inner array
     for (int j = 0; j < myArray[i].length; j  ) {
          System.out.println("How many elements in myArray["   i   "]["   j   "]?");
          size = s.nextInt();
          myArray[i][j] = new int[size];
     }
}

CodePudding user response:

You're in luck. Java doesn't have 2D or 3D arrays, at all. It only has arrays-of-arrays. The snippet of code you pasted is merely syntax sugar at work.

Thus:

int[][] chessboard = new int[8][];
int row0 = new int[8];
chessboard[0] = row0;

An int[][] is simply a 1D array where each element in your array is, itself, an int[]. See, above, how we make a 1D int array and assign it to the 0 slot of the chessboard variable, thus proving chessboard is 1-dimensional just the same.

Forget about the syntax sugar and make the arrays as above, then you're in full control and can make each 'inner' array whatever size you want it to be. The only weirdness is how to initialize them. new int[8][] is the non-syntax sugar version: That makes a 1D array of int arrays with room for 8 int[], and like all normal array initializes, starts out with 8 null pointers, entirely identical to e.g. String[] x = new String[8], which makes no strings, and after that e.g. x[0] would be null.

You're then free to call chessboard[0] = new int[8], etcetera.

  • Related