0

I want to build a 2D array from N (one-dimensional) arrays. The only problem is, as far as I can tell, the only way to declare a multi-dimensional array in Java requires you to specify all inner dimension sizes, and those sub-arrays get created. In this case, this seems wasteful, since they will be overwritten

In C++, I could do this:

Object** arr = new Object*[n];

for(int i=0;i<n; ++i)
{
      arr[i] = getObjArr();
}

In Java, you have to say this:

Object[][] arr = new Object[n][0]; //inner dimension is required

Each of those n zero-length arrays will be created, only to get overwritten as the array is populated. Is there a way to declare a multi-dimensional array (similar to the pointer to pointer(s) syntax of C) without allocating the inner arrays?

1

2 Answers 2

2

Sure. I don't know why you think you have to do that!

   double[][] foo = new double[2][];

is perfectly fine. The "inner" arrays will be null.

Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps you're switching indexes wrt "row" vs. "column" major (for lack of a better thing to call that)?
1

Inner dimensions do not have to be specified. This is legal in Java:

Object[][] arr = new Object[n][];

This creates an array of n elements, where each element has type Object[]. Since you did not specify an inner dimension, those n elements are all initialized to null. You can then assign any Object[] you want to any of those n array elements.

For higher-dimensional arrays, the rule (if you don't have an initializer) is that you can say new T followed by one or more specified dimensions ([some-value]), followed by zero or more [] for unspecified dimensions. You can't have [] followed by [value].

3 Comments

Well I thought I had already tried that, but sure enough, it does work!
Maybe you tried new Object[][n]? That's not legal.
No, I understand that Java is row-major, just like C. I think I got confused by an unrelated error.

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.