Adam Sh
Adam Sh

Reputation: 8577

Java - function as parameter

I read the next answer about passing function as parameter.

Still, I don't get the idea. My function can get any function: sin(x), cos(x), etc.

As I understood, I can create an interface, for example:

public interface functionI<T> {

}

that would wrap It.

Now I have my function:

    public void needToDo(functionI<Integer> a, int x0Par, int hPar){
}

(needToDo, for example, need to substitue the x of the function n x0par and hPar, and find the Max. If I got sin(x), I need to find the max of sin(x0Par) and (sin(hPar)).

I didn't understand how I use it in my function. How will I know what to do when I got the function, that can be anything (polynomial, sin(x), and so on)

Upvotes: 2

Views: 2872

Answers (2)

Tom
Tom

Reputation: 44821

Something like this:

public interface Function1<RESULT,INPUT> {
    RESULT call(INPUT input);
}

public class Sin implements Function1<Double,Double> {
    public static final Sin instance = new Sin();
    private Sin() {
    }
    public Double call(Double x) {
        return Math.sin(x);
    }
}

public Double needToDo(Function1<Double,Double> aFunction, Double x0Par, Double hPar) {
   Double d1 = aFunction.call(x0Par);
   Double d2 = aFunction.call(hPar);
   return d1 > d2 ? d1 : d2;
}

public static void main(String[] args) {
    Double x0Par = 10.2;
    Double hPar = 1.9;
    Double ret = needToDo(Sin.instance, x0Par, hPar);
    System.out.println(ret);
}

Upvotes: 5

Cyberfox
Cyberfox

Reputation: 1145

It doesn't quite work like that; you cannot pass arbitrary functions as parameters in Java, instead you pass objects which have specific, often generic sounding, functions.

So you could define a MathOperation interface, which has an execute method, taking a double and returning a double.

public interface MathOperation {
  double execute(double x);
}

and then you can create

public class Sin implements MathOperation {
  public double execute(double x) { return Math.sin(x); }
}

and have a function that uses it like

public void needToDo(MathOperation op, double x) {
  System.out.println(op.execute(x));
}

You could create an on-the-fly function for needToDo like

...
needToDo(new MathOperation() {
    public double execute(double x) { return x * 2.0; }
});
...

But you can't pass Math.sin as a parameter. There are reflection tricks you can do, but that's another issue.

Upvotes: 3

Related Questions