Laurena
Laurena

Reputation: 21

How do I create a 2d array made of 2d int arrays in java?

I want to create a 2d array that is made of smaller 2d integer arrays, to overall make a matrix graph. Instead of storing integers in the bigger array I would store 2d integer arrays.

Edit: I think drew the array I want incorrectly. What I meant was I want to create a grid (matrix - 2d array) where inside each cell of the grid instead of there being stored a int, boolean, etc. I would like to store a 2d int array in each cell of the grid.

I was thinking something like int[int[][]][int[][]]. But realized that wouldn't work since the outer array isn't an integer array, it is just a general array made of integer arrays.

I found codes in other questions here that have a 2d array of objects (ex. room[][]) but I don't think that would be necessary since the array I'm trying to make is made of int[][] arrays, correct?

So how could I got about this?

Thanks in advance!

Upvotes: 0

Views: 70

Answers (2)

VN'sCorner
VN'sCorner

Reputation: 1552

In Java multi-dimentional arrays are implemented as array of arrays approach and not matrix form. To implement the data structure provided in the request array has to be implemented as below,

Data Structure :

{{{0,1}, {{0,1},
  {2,3}}, {2,3}},
 {{0,1}, {{0,1},
  {2,3}}, {2,3}}}

Array Declaration and assignment :

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

      int[][][][] q =new int[2][2][2][2];

      q[0][0][0][0] = 0;
      q[0][0][0][1] = 1;
      q[0][0][1][0] = 0;
      q[0][0][1][1] = 1;
      q[0][1][0][0] = 2;
      q[0][1][0][1] = 3;
      q[0][1][1][0] = 2;
      q[0][1][1][1] = 3;

      q[1][0][0][0] = 0;
      q[1][0][0][1] = 1;
      q[1][0][1][0] = 0;
      q[1][0][1][1] = 1;
      q[1][1][0][0] = 2;
      q[1][1][0][1] = 3;
      q[1][1][1][0] = 2;
      q[1][1][1][1] = 3;
    }
}

Upvotes: 1

Eklavya
Eklavya

Reputation: 18410

It seems 4D array, use int[][][][] to store data.

4D array means 2D array of 2D array

Example: int[][][][] arr = new int[10][20][10][10]

It creates a 2D array of 10X20 size where for each cell there is 2D array of 10X10.

Upvotes: 1

Related Questions