Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable dimensioned array in Java?

Tags:

java

arrays

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

like image 451
Logg Avatar asked Apr 14 '11 23:04

Logg


People also ask

What is variable length array in Java?

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

Can you use variables to set size of array Java?

You can't change the size of an array.

How do you declare an array variable in Java?

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};

Can you have an array of variables in Java?

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.


2 Answers

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

like image 80
jberg Avatar answered Sep 24 '22 13:09

jberg


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.

like image 45
Paŭlo Ebermann Avatar answered Sep 20 '22 13:09

Paŭlo Ebermann