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.
一个需要更多工作的替代方法是使用底层的平面数组表示来实现自己的类型,在这里你可以在内部计算索引,并提供具有vararg参数的访问器方法。我不知道它是否完全可行,但可能值得一试...
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屋!