我需要能够拥有一个 n 维字段,其中 n 基于构造函数的输入。但我什至不确定这是否可能。是吗?
快速解决方案:您可以用非泛型来近似它ArrayList
of ArrayList
...根据需要深入。然而,这在快速使用时可能会变得很尴尬。
需要更多工作的替代方案可能是使用底层平面数组表示来实现您自己的类型,您可以在内部计算索引,并提供带有可变参数参数的访问器方法。我不确定它是否完全可行,但可能值得一试......
粗略的示例(未经测试,没有溢出检查,错误处理等,但希望传达基本思想):
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];
}
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)