Java n-dimensional array
•
Java
I need to be able to have an n-dimensional field, where n is the input based on the constructor But I'm not even sure if it's possible Is it?
Solution
Quick solution: you can approximate it with a non - Generic ArrayList of ArrayList that matches the depth you need However, this can be awkward to use quite quickly
An alternative that requires more work may be to use the underlying flat array representation to implement your own type, where you can internally calculate the index and provide the accessor method with the vararg parameter I don't know if it's completely feasible, but it may be worth trying
Rough style (not tested, no overflow check, error handling, etc., but want to convey 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]; } ... }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码