Gengar
Gengar

Reputation: 133

Dynamic 2nd dimension in array

Is there a way to create a two-dimensional array in java where 2nd dimension of the array has a variable number of elements?

For instance, if I knew the elements beforehand, I could declare the entire array at once like this. int[][] runs = {{1, 4, 7}, {2, 3}, {1}};

However, I do not know the values beforehand. I would like to partially declare the array to do something like this:

int[][] runs = new int[3];

And then fill in each element of the 1st dimension with a an array of integers. But I get an error.

Upvotes: 0

Views: 224

Answers (3)

zmirc
zmirc

Reputation: 825

The 2nd dimension can be variable. Take a look here:

int[][] runs = new int[3][];
runs[0] = new int[55];
runs[0][3] = 412532;
runs[0][54] = 444;
runs[1] = new int[]{1, 2};
runs[2] = new int[]{2,3,4,2,4,5,3,5,2,6};

You can do whatever you want after you set the 1st dimension of the array, as shown in the example.

Upvotes: 0

Mena
Mena

Reputation: 48404

If I understand your question correctly the answer is pretty simple.

You're trying to create an asymmetric multi-dimentional array.

You can initialize your array with a known 1st level size, and an unknown 2nd level size.

For instance:

int[][] runs = new int[3][];

Then...

runs[0] = new int[]{1,2,3};
runs[1] = new int[]{4};
runs[2] = new int[2]; // no elements defined, defaults to 0,0
System.out.println(Arrays.deepToString(runs));

Output:

[[1, 2, 3], [4], [0, 0]]

Upvotes: 3

Kon
Kon

Reputation: 10810

int[][] runs = new int[3][];

Will do the trick.

Then you need to initialize each dimension.

runs[0] = new int[5];
runs[1] = new int[x];
//and so on

The initialization of each dimension can be done at any time later, just make sure to avoid accessing the elements before initialization or you'll get a NullPointerException

Upvotes: 0

Related Questions