Creating an n-dimensional array in Java at runtime

I have a String that contains arrays. Example:

"[[1, 2], [4, 5], [7, 8]]" 

Now I want to make a Java array from this. I created a function to get the dimensions and a recursive function to get each element of the array. So I have every 1-D array, but I would like to know if there is a way in Java to create a dimension array that I found at runtime? Dimension is returned as an array. For example, for the above example, the size is:

 [3, 2] 

EDIT: Is there a way to create a real array from this information? The measurement [3, 2] is just an example. I can have [3, 2, 4, 5]. Can an array be generated from this information at runtime? I do not have this information at compile time.

There is some problem, I can not comment on the answers. So, I am editing here.

+2
java arrays dynamic multidimensional-array
source share
2 answers

If you are doing numerical work, you should probably use a library. For example, my Vectorz open source library provides the correct support for multidimensional arrays / matrices (with double s).

Then you can just do something like:

 INDArray m=Arrayz.parse("[[1, 2], [4, 5], [7, 8]]"); 

The INDArray object encapsulates all multidimensionality, so you donโ€™t have to worry about writing large nested loops all the time, and it also provides many other functions and features that regular Java arrays do not have.

+2
source share

The main problem is that you cannot directly refer to the N dimensional array in the code.

Fortunately, java has a bit of a dirty hack that allows you to somehow work with N dimensional arrays:

Arrays are objects like any other non-primitive in java.

Therefore, you can have:

 // Note it Object o not Object[] o Object o = new Object [dimensionLengh]; 

You can use the recursive method to create it.

 Object createMultyDimArray(int [] dimensionLengths) { return createMultyDimArray(dimensionLengths, 0); } Object createMultyDimArray(int [] dimensionLengths, int depth) { Object [] dimension = new Object[dimensionLengths[depth]]; if (depth + 1 < dimensionLengths.length) { for (int i=0; i < dimensionLengths[depth]; i++) { dimension[i] = createMultyDimArray(dimensionLengths, depth+1); } } return dimension; } 

To use this, you need to cast from Object to Object [] .

Java is type safe on arrays and errors can cause a ClassCastException. I would recommend you also read about how to create arrays using java reflection: http://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html .

+1
source share

All Articles