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?

stands2reason
  • 672
  • 2
  • 7
  • 18

2 Answers2

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.

BadZen
  • 4,083
  • 2
  • 25
  • 48
  • Perhaps you're switching indexes wrt "row" vs. "column" major (for lack of a better thing to call that)? – BadZen Apr 14 '15 at 04:33
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].

ajb
  • 31,309
  • 3
  • 58
  • 84