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

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

I would actually argue the need to use a primitive array there, as opposed to writing an abstraction over it that creates the "arbitrary amount of dimensions" paradigm and hides the actual storage. It may be dependent on the actual usage pattern though.
+1 Multi-dimensional arrays are not useful, particularly in object-oriented languages that make it trivial to wrap your array in some more meaningful data structure. Just use a flat array and interpolate your indices.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.