stands2reason
stands2reason

Reputation: 730

Create array of arrays (2D) without initializing inner arrays in Java

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?

Upvotes: 0

Views: 261

Answers (2)

ajb
ajb

Reputation: 31699

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].

Upvotes: 1

BadZen
BadZen

Reputation: 4274

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.

Upvotes: 2

Related Questions