0

Is there some kind of datatype that supportes an n-dimensional array? The problem is that when an array is created the number of dimensions a fixed from the beginning in the datatype:

T[] oneDimensional = ...
T[][] twoDimensional = ...
T[][][] threeDimensional = ...
...
T[]???[] nDimensional = ...

I can create this nDimensinal arrays as shown in the following code, but it seems that there is no way to save them in a variable except as an Object. But with an Object I can't work with the array.

@SuppressWarnings("unchecked")
public static <T> ??? createMultidimensionalArray(Class<T> clazz, int dimensions, int dimensionLength) {
    int[] dimArr = new int[dimensions];
    for (int i = 0; i < dimensions; i++) {
        dimArr[i] = dimensionLength;
    }
    ??? targetArray = (???) Array.newInstance(clazz, dimArr);
}

The question is: What datatype could fit the ????


Another attempt of me would be to create a class with some kind of linked array where every dimension gets it's own linked instance of that class. This idea is shown here. Still, since this idea would no longer use native arrays I'd like to avoid it.

Japhei
  • 565
  • 3
  • 18
  • Not sure if this post might help you out. https://stackoverflow.com/questions/4770926/java-n-dimensional-arrays – Rhett Harrison Jul 06 '22 at 13:52
  • @RhettHarrison & Federuco klez Culloca Not realy. These posts are about creating n-dimensional arrays. I would rather like to know how to store them. The accepted answer (https://stackoverflow.com/a/4770943/13148560) of this post shows the way I'd like to avoid as explained above. – Japhei Jul 06 '22 at 14:04
  • 2
    Then you'll need to explain why you want to keep using native arrays in the first place. And even then I can't think of a good way to do this with native arrays. – Federico klez Culloca Jul 06 '22 at 14:06
  • @FedericoklezCulloca Simply accessebility and dependency of the rest of the program. Otherwise I could just put an endless amount of lists inside each other. I can't think of a good way to do this whith arrays eigher. Thats why I asked this question in the first place. – Japhei Jul 06 '22 at 14:10
  • 1
    There isn't a better way. Sorry. Java doesn't have a syntax or data types for handling arrays with an indefinite number of dimensions. (And I can't think of any PL that does ...) – Stephen C Jul 06 '22 at 14:48
  • 1
    *"The question is: What datatype could fit the ????"* - The only Java types that would (slightly) work here are `Object` or `Object[]`, I think. And you know where that will lead ... – Stephen C Jul 07 '22 at 01:03

0 Answers0