Java N-Dimensional Arrays

Quick solution: you could approximate it with a non-generic ArrayList of ArrayList of … going as deep as you need to. However, this may get awkward to use pretty fast.

An alternative requiring more work could be to implement your own type using an underlying flat array representation where you calculate the indexing internally, and providing accessor methods with vararg parameters. I am not sure if it is fully workable, but may be worth a try…

Rough example (not tested, no overflow checking, error handling etc. but hopefully communicates the basic idea):

class NDimensionalArray {
  private Object[] array; // internal representation of the N-dimensional array
  private int[] dimensions; // dimensions of the array
  private int[] multipliers; // used to calculate the index in the internal array

  NDimensionalArray(int... dimensions) {
    int arraySize = 1;

    multipliers = new int[dimensions.length];
    for (int idx = dimensions.length - 1; idx >= 0; idx--) {
      multipliers[idx] = arraySize;
      arraySize *= dimensions[idx];
    }
    array = new Object[arraySize];
    this.dimensions = dimensions;
  }
  ...
  public Object get(int... indices) {
    assert indices.length == dimensions.length;
    int internalIndex = 0;

    for (int idx = 0; idx < indices.length; idx++) {
      internalIndex += indices[idx] * multipliers[idx];
    }
    return array[internalIndex];
  }
  ...
}

Leave a Comment