Java N 维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4770926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java N-Dimensional Arrays
提问by skeggse
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?
我需要能够有一个 n 维字段,其中 n 基于构造函数的输入。但我什至不确定这是否可能。是吗?
采纳答案by Péter T?r?k
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.
快速解决方案:你可以用一个非泛型ArrayList
的ArrayList
of ...来近似它,尽可能深入。但是,这可能会因为使用得很快而变得尴尬。
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];
}
...
}
回答by casablanca
Here's a nice article that explains how to use reflection to create arrays at run-time: Java Reflection: Arrays. That article explains how to create a one-dimensional array, but java.lang.reflect.Array
also contains another newInstance
method to create multi-dimensional arrays. For example:
这是一篇很好的文章,解释了如何在运行时使用反射来创建数组:Java 反射:数组。那篇文章解释了如何创建一维数组,但java.lang.reflect.Array
也包含另newInstance
一种创建多维数组的方法。例如:
int[] dimensions = { 10, 10, 10 }; // 3-dimensional array, 10 elements per dimension
Object myArray = Array.newInstance(String.class, dimensions); // 3D array of strings
Since the number of dimensions is not known until runtime, you can only handle the array as an Object
and you must use the get
and set
methods of the Array
class to manipulate the elements of the array.
由于直到运行时才知道维数,因此您只能将数组作为 an 处理,Object
并且必须使用类的get
和set
方法Array
来操作数组的元素。