Variable dimensioned array in Java?

2020-03-13 06:42发布

问题:

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

回答1:

I would just use flat 1-dimensional arrays and index based on dimension, i and j.



回答2:

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.



标签: java arrays