我写了一些c#代码,它实现了几个函数的传递.我使用了代表.
public delegate float Func(float x);
public Dictionary<string, Func> Functions = new Dictionary<string, Func>();
Run Code Online (Sandbox Code Playgroud)
填写字典:
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); });
Run Code Online (Sandbox Code Playgroud)
我使用这些函数来查找它们的最大值和其他一些任务.
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;
}
Run Code Online (Sandbox Code Playgroud)
我怎么能用Java做到这一点?
我不知道如何在Java中使用委托.
你可以使用这样的界面:
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);
}
Run Code Online (Sandbox Code Playgroud)