Looping through arrays

Hello,

I am developing a program which contains redundant code as it contains too many methods that loop through the same two dimensional array all the time.

The reason why the code is redundant is because I need to perform a different action to different values in the array each time (depending on whether statement is true or false).

What I want to try and do is create one single method which loops through the array and returns a boolean value.

The method needs to take something like an if statement as a parameter so that I can stop searching through the array when the value of some element in array satisfies the if statement.

How do I do this? How do I cut down the amount of code that searches through the same array all the time.

Hope someone can understand

Thanks

[825 byte] By [ANDREWP7a] at [2007-11-27 3:05:22]
# 1
As you can't pass "function pointers" in Java, you will have to look at something like the Visitor pattern (Google it).Truth be told, looping through an array doesn't seem like worth refactoring. Is your code going to get clearer or even shorter (NOT the same thing!)? I doubt it.
Herko_ter_Horsta at 2007-7-12 3:50:50 > top of Java-index,Java Essentials,Java Programming...
# 2

Well, it's hard to get less verbose that foreach loops. In theory you could define an interface taking an element and returning boolean, then create a (probably anonymouis) class instance for each process. Then you could have a method which does the loop. Can't see many cases where it would be messier than a simple set of loops, though.

malcolmmca at 2007-7-12 3:50:50 > top of Java-index,Java Essentials,Java Programming...
# 3

Are you looking to do something like this?

interface Predicate {

boolean apply(int arg);

}

class IsEven implements Predicate {

public boolean apply(int arg) {

return arg % 2 == 0;

}

}

public class PredicateExample {

public boolean searchMaxtrix(int[][] m, Predicate p) {

for (int[] row : m)

for(int x : row)

if (p.apply(x))

return true;

return false;

}

}

DrLaszloJamfa at 2007-7-12 3:50:50 > top of Java-index,Java Essentials,Java Programming...