Java N 维数组 [英] Java N-Dimensional Arrays
问题描述
我需要能够有一个 n 维字段,其中 n 基于构造函数的输入.但我什至不确定这是否可能.是吗?
I need to be able to have an n-dimensional field where n is based on an input to the constructor. But I'm not even sure if that's possible. Is it?
推荐答案
快速解决方案:你可以用一个非泛型的 ArrayList
的 ArrayList
来近似它...尽可能深入.但是,这可能会很快使用起来很尴尬.
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];
}
...
}
这篇关于Java N 维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!