Re: Can a method be a parameter of another method in Java?
Shawn wrote:
Hi,
Could you provide me one more example to achieve the following effect in
Java? Thank you very much.
var a = [1,2,3];
for (i=0; i<a.length; i++)
{
a[i] = a[i] * 2;
}
for (i=0; i<a.length; i++)
{
alert(a[i]);
}
Doing something to every element of an array is pretty common, and you
can write a function that does it for you:
function map(fn, a)
{
for (i = 0; i < a.length; i++)
{
a[i] = fn(a[i]);
}
}
Now you can rewrite the code above as:
map( function(x){return x*2;}, a );
map( alert, a );
I tried the following file Test.java. It didn't work.
/*
For testing passing a method as a method parameter
*/
interface Mapper {
void map(int[] d);
}
class Test {
void doSomethingToArray(Mapper m, int[] aArray) {
m.map(aArray);
} //end of method doSomethingToArray
Mapper squareArray = new Mapper() {
void map(int[] a)
{
for (int i=0; i<a.length; i++)
{
a[i] *= a[i];
}
}
}
Mapper printArray = new Mapper() {
void map(int[] a)
{
for (int i=0; i<a.length; i++)
{
System.out.println(a[i]);
}
}
}
static int[] a={2, 4, 6, 8};
public static void main(String[] args)
{
doSomethingToArray(squareArray, a);
doSomethingToArray(printArray, a);
}
} //end of class Test
Below is the error message. I cannot solve it. Back to the interface
issue, I am not allowed to instantiate an interface even I implement its
method?
Thank you very much for your help.
>javac Test.java
----------
1. ERROR in Test.java (at line 25)
Mapper printArray = new Mapper() {
^^^^^^
Syntax error on token "Mapper", ";", "," expected
----------
2. ERROR in Test.java (at line 39)
doSomethingToArray(squareArray, a);
^^^^^^^^^^^
Cannot make a static reference to the non-static field squareArray
----------
3. ERROR in Test.java (at line 40)
doSomethingToArray(printArray, a);
^^^^^^^^^^
Cannot make a static reference to the non-static field printArray
----------
3 problems (3 errors)