Reputation: 120
How can I iterate over a n-dimensional array (n is unknown)?
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.
Upvotes: 4
Views: 2297
Reputation: 48817
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
Upvotes: 2
Reputation: 12347
In C/C++ multidimensional arrays (int[][]
) are represented in a flat way in the memory and the indexing operators are translated into pointer arithmetics. 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. 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++
To do that see other answers.. :-)
Upvotes: 1
Reputation: 2365
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));
}
});
Upvotes: 2