0

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.

1
  • How about using List? Commented Sep 15, 2013 at 20:33

3 Answers 3

3

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for teaching me about the deepToString() method. I've always quickly coded my own toStrings for multi-D arrays.
0
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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.