我怎样可以遍历一个n维数组(n是未知的)?
我在C++中找到了通过运行数组的内存区域来完成遍历的结果,但我不知道在JAVA中是否可以这样做。
我怎样可以遍历一个n维数组(n是未知的)?
我在C++中找到了通过运行数组的内存区域来完成遍历的结果,但我不知道在JAVA中是否可以这样做。
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));
}
});
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);
}
}
}
然后,在调用时:
// 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);
这将打印:
1
2
3
4
5
6
int[][]
)以平面方式表示在内存中,索引运算符被转换为指针算术运算。这就是为什么在这些语言中很容易和直接进行的原因。