I have a String which contains arrays. Example:
\"[[1, 2], [4, 5], [7, 8]]\"
Now, I want to make an actual Java array out of this. I have c
If you are doing numeric work then you should probably use a library. For example my open source library Vectorz provides proper 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 the multidimensionality so you don't need to worry about writing big nested loops all the time, plus it provides a lot of other functions and capabilities that normal Java arrays don't have.
The main problem is that you can't reference an N dimensional array in code directly.
Fortunately java has a bit of a dirty hack that lets you have some way to work with N dimensional arrays:
Arrays are objects like every other non-primative in java.
Therefore you can have:
// Note it's Object o not Object[] o
Object o = new Object [dimensionLengh];
You can use a recursive method to build it up.
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 will need to cast from Object
to Object []
.
Java is type safe on arrays and mistakes 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.