2

I wrote some c# code, which implements the transfer of several functions. I used delegates for it.

public delegate float Func(float x);
public Dictionary<string, Func> Functions = new Dictionary<string, Func>();

Fill in dictionary:

Functions.Add("y=x", delegate(float x) { return x; });
        Functions.Add("y=x^2", delegate(float x) { return x*x; });
        Functions.Add("y=x^3", delegate(float x) { return x*x*x; });
        Functions.Add("y=sin(x)", delegate(float x) { return (float)Math.Sin((double)x); });
        Functions.Add("y=cos(x)", delegate(float x) { return (float)Math.Cos((double)x); });

and I use these functions to find max of them and some other tasks.

private float maxY(params Func[] F)
    {
        float maxYi = 0;
        float maxY = 0;
        foreach (Func f in F)
        {
            for (float i = leftx; i < rightx; i += step)
            {
                maxYi = Math.Max(f(i), maxYi);
            }
            maxY = Math.Max(maxY, maxYi);
        }
        return maxY;
    }

How can I do this in Java?
I don`t know how to use delegates in Java.

yoozer8
  • 7,361
  • 7
  • 58
  • 93
finder_sl
  • 307
  • 4
  • 13

2 Answers2

7

You can use an interface like this:

public static void main(String... args) throws Exception {
    Map<String, Computable> functions = new HashMap<String, Computable>();
    functions.put("y=x", new Computable() {public double compute(double x) {return x;}});
    functions.put("y=x^2", new Computable() {public double compute(double x) {return x*x;}});

    for(Map.Entry<String, Computable> e : functions.entrySet()) {
        System.out.println(e.getKey() + ": " + e.getValue().compute(5)); //prints: y=x: 5.0 then y=x^2: 25.0
    }
}

interface Computable {
    double compute(double x);
}
assylias
  • 321,522
  • 82
  • 660
  • 783
1

Java doesn't have delegates, but you can achieve the same effect by declaring an interface with only one method.

interface Function {
    float func(float x);
}

Functions.Add("y=x", new Function { public float func(float x) { return x; } });

(sorry for the possible syntax errors, I'm not very familiar with the Java syntax)

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758