[英]Iterate over n-dimensional arrays
How can I iterate over a n-dimensional array ( n is unknown)? 如何迭代n维数组( n未知)?
I've found results for C++ where one would simply run through the memory region of the array, but I don't know if I can do that in JAVA. 我找到了C ++的结果,其中一个只是运行数组的内存区域,但我不知道我是否可以在JAVA中执行此操作。
I found this somewhere else. 我在其他地方找到了这个。 It's a rather nice recursive solution to your problem: 这是一个相当不错的递归解决方案:
interface Callback {
void visit(int[] p); // n-dimensional point
}
void visit(int[] bounds, int currentDimension, int[] p, Callback c) {
for (int i = 0; i < bounds[currentDimension]; i++) {
p[currentDimension] = i;
if (currentDimension == p.length - 1) c.visit(p);
else visit(bounds, currentDimension + 1, p, c);
}
}
visit(new int[] {10, 10, 10}, 0, new int[3], new Callback() {
public void visit(int[] p) {
System.out.println(Arrays.toString(p));
}
});
This could suit your needs: 这可以满足您的需求:
public interface ElementProcessor {
void process(Object e);
}
public static void iterate(Object o, ElementProcessor p) {
int n = Array.getLength(o);
for (int i = 0; i < n; i++) {
Object e = Array.get(o, i);
if (e != null && e.getClass().isArray()) {
iterate(e, p);
} else {
p.process(e);
}
}
}
Then, when calling: 然后,在打电话时:
// the process method will be called on each element of the n-dimensional
ElementProcessor p = new ElementProcessor() {
@Override
public void process(Object e) {
// simply log for example
System.out.println(e);
}
};
int[] a1 = new int[] { 1, 2 };
int[][] a2 = new int[][] { new int[] { 3, 4 }, new int[] { 5, 6 } };
iterate(a1, p);
iterate(a2, p);
This prints: 这打印:
1
2
3
4
5
6
In C/C++ multidimensional arrays ( int[][]
) are represented in a flat way in the memory and the indexing operators are translated into pointer arithmetics. 在C / C ++中,多维数组( int[][]
)在内存中以平面方式表示,索引操作符被转换为指针算术。 That is why it is easy and straightforward to do that in those languages. 这就是为什么用这些语言做到这一点简单易行的原因。
However this is not the situation in Java, multi-dimensional arrays are arrays of arrays. 然而,这不是Java的情况,多维数组是数组的数组。 As types are strictly checked, indexing in an array of arrays yields an array type as a result, not the type that the inner arrays contain. 在严格检查类型时,数组数组中的索引会产生数组类型,而不是内部数组包含的类型。
So tho answer the question: no, you cannot do that in Java as simply as in C/C++ 所以回答这个问题: 不,你不能像在C / C ++中那样在Java中做到这一点
To do that see other answers.. :-) 为此,请参阅其他答案.. :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.