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