Let's say I have a multi-dimensional array as a member of a class and a lot of methods, that loop through every element of the array and then operate on it. The code might look like this:
public class Baz {
private Foo[][] fooArray = new Foo[100][100];
public Baz() {
for (int i = 0; i < fooArray.length; i++) {
for (int j = 0; j < fooArray[i].length; j++) {
// Initialize fooArray
}
}
}
public void method1() {
for (int i = 0; i < fooArray.length; i++) {
for (int j = 0; j < fooArray[i].length; j++) {
// Do something with fooArray[i][j]
}
}
}
public void method2() {
for (int i = 0; i < fooArray.length; i++) {
for (int j = 0; j < fooArray[i].length; j++) {
// Do something else with fooArray[i][j]
}
}
}
// and so on
}
Now, since the code for the loop is always the same, only the operation within the loop changes, is there any way the code for looping could be somehow refactored into a seperate method? It would be so nice to be able to do
doInLoop(functionToExecute());
What would be the nearest substitute for doing something like this, if it is even possible?