switch (dimensions) {
case 1: double[] array = new double[10]; break;
case 2: double[][] array = new double[10][]; break;
case 3: double[][][] array = new double[10][][]; break;
case 4: double[][][][] array = new double[10][][][]; break;
case 5: double[][][][][] array = new double[10][][][][]; break;
case 6: double[][][][][][] array = new double[10][][][][][]; break;
default: System.out.println("Sorry, too many dimensions"); break;
}
Is there a way to do the above in a better way? I want it to be able to create an array of any number of dimensions, also...
In computer programming, a variable-length array (VLA), also called variable-sized or runtime-sized, is an array data structure whose length is determined at run time (instead of at compile time).
You can't change the size of an array.
We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};
Declaring an Array Variable in JavaYou can use a Java array as a field, static field, a local variable, or parameter, just like any other variable. An array is simply a variation of the data type. Instead of being a single variable of that type, it is a collection of variables of that type.
I would just use flat 1-dimensional arrays and index based on dimension, i and j.
As already said, you can't really use such an array, as you would need different code for each dimension.
Creating such an array is doable, though, using reflection:
import java.lang.reflect.Array;
private Class<?> arrayClass(Class<?> compClass, int dimensions) {
if(dimensions == 0) {
return compClass;
}
int[] dims = new int[dimensions];
Object dummy = Array.newInstance(compClass, dims);
return dummy.getClass();
}
public Object makeArray(int dimensions) {
Class<?> compType = arrayClass(double.class, dimensions-1);
return Array.newInstance(compType, 10);
}
You then would have to use reflection to access your array, or cast it to Object[] (which works for all dimensions > 1), and then manipulate only the first level. Or feed it to a method which needs the right type of array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With