Re: Can a method be a parameter of another method in Java?
Ingo R. Homann wrote:
Besides the missing ';', there is another design-flaw IMHO. I would do
it like this:
interface Mapper {
int map(int a);
}
class Test {
void doSomethingToArray(int[] as, Mapper m) {
for(int i=0;i<as.length;i++) {
as[i]=m.map(as[i]);
}
}
}
Mapper square=new Mapper() {
int map(int i) {
return i*i;
}
}
Mapper print=new Mapper() {
int map(int i) {
System.out.println(i);
return i; // (*)
}
}
(*) here you can see, that "printing" is not really a kind of
"Mapper"-function.
Ciao,
Ingo
Thank you. Could you kindly provide "public static void main() " to show
me how to use it. As you see, I am a little lost here: in the same Java
file or in the different file? If in the same file, what the file name
should be?(Test.java or interface.java?) Do I have to make
doSomethingToArray static?
I still like my previous not-running program, because in yours, as you
said, Mapper print is "silly" and in the for loop inside
doSomethingToArray, as[i] = m.map(as[i]) is not needed in my program. My
code is more intuitive. The reason I want to pass a method as a
parameter into another method is to have more abstraction(clear mind
clutter). Your implementation brings other extra into the code. My goal
is half-achieved, though.