0

I would like to initialize a float[][][] object in Java. For instance,

float[][][] x = new float[1][2][3]

As you can see the integers 1, 2 and 3 are known by default. Now I have a int[] defining these numbers ( dimensions ) of the array like,

int[] shape = { 1 , 64 , 64 , 3 }

From this array, how can I build an object like,

float[][][][] y = new float[1][64][64][3]

Note: The length of the shape object is not predefined. Hence the dimensions of the resulting float[] object will also vary.

How do we dynamically create a float matrix ( like float[][] or even float[][][] ) from a given int[] which defines its shape.

Shubham Panchal
  • 4,061
  • 2
  • 11
  • 36
  • 1
    Maybe you can use Object[]...[] instead of float[]...[]. In this case you can simply add new dimensions while iterate shape array and then cast the resulting matrix of objects to matrix of floats. This is just an idea – Nikita Ryanov Sep 09 '19 at 08:13
  • 2
    You could use the [newInstance()](https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html#newInstance(java.lang.Class,%20int...)) method to create such an array but you would have to use `Float` instead of `float` for your element type and I'm not sure how you could dynamically cast it to an array of variable dimensions. – Mihir Kekkar Sep 09 '19 at 08:21
  • 4
    What do you need it for? You couldn't actually use the array in your code, since you couldn't express the compile-time type of the array with a variable number of dimensions. You would constantly need reflection to use it. – Erwin Bolwidt Sep 09 '19 at 08:22
  • 2
    According to [this answer](https://stackoverflow.com/questions/3104504/is-it-possible-to-dynamically-build-a-multi-dimensional-array-in-java/3104931#3104931) it appears to be possible to modify the array after it is created by recursing through each dimension. – Mihir Kekkar Sep 09 '19 at 08:26

1 Answers1

0

You can do reflection to create the array and then type-cast it to make it useful.

float[][][][] x = (float[][][][]) Array.newInstance(Float.TYPE, shape);

This assumes that you at least know the number of dimensions upfront.

If you don't know that, you can still create the array, but you cannot cast it to a static type anymore (it will just be an Object). This will make it hard to write code that uses the array.

Thilo
  • 257,207
  • 101
  • 511
  • 656