0

Is it possible to have an n dimensional array in Java without having to explicitly specify the number of dimensions?

I.e. if I wanted a 2D array of ints I'd do:

int[][] myArray = new int[a][b];

For the above I've had to specify that the myArray variable is of type int[][]. What I'm asking is whether there's the possibility to declare a variable that is an array of n dimensions without having to know n in advance.

I.e. If I had the variable test, test could be of type int[][] or int[][][] or int[][][][][][][][][][][] - you get the idea. I just want to define test without having to define the number of dimensions.

I'm sure the above kind of breaks the type system in Java so I'm open to any ideas as I think I'm approaching this the wrong way.

To give you a bit of context I've developed an algorithm to find an integer in a 2D array of integers that are sorted by both row and column in ascending order. I've noticed that it will work with any dimension array and would thus like to make it more generic. However, I don't fancy defining a function for every possible dimension of array to be passed as a parameter since the dimensions could (unlikely as it is) be anywhere from 1D to infinityD - hence the question.

This is also just for my own curiosity as to whether this can be done for any dimension array. I don't know whether this potentially can't be done using Java's built in facilities and I'd be better building my own class system to support multi-dimension arrays in this situation.

goastler
  • 223
  • 2
  • 6
  • Yes, create an `ArrayList` and keep adding more of those to it, you probably want this: http://stackoverflow.com/questions/4770926/java-n-dimensional-arrays – Idos Mar 15 '17 at 13:15

1 Answers1

0

You can not define an array as unknown-dimensional. But you can make your own class like NDimensionalArray, that would wrap array of another NDimensionalArray instances, and implement getter like getValue(int indexes...), and dimension()

class NDimensionalArray {
    NDimensionalArray[] arrays;

    int value;

    int getValue(int... indexes) {
        if (indexes.length == 0) return value;
        return arrays[indexes[0]].getValue(indexes[1],indexes[2],...,indexes[n-1]);
    }

    void setValue(int value, int... indexes) {
        // implement simillary to getValue
    }

    int getDimension() {
        if (arrays == 0 || arrays.length == 0) return 0;
        return arrays[0].getDimension() + 1;
    }
}

that's not a working class, but only an idea, creating the entire structure is on your own. You would need to implement all the index and null checks.

fairtrax
  • 416
  • 2
  • 8