假设我有一个带有参数的函数列表:f(a),g(b),h(c)
我现在想要创建一个Vector,如下colour label
#F8766D setosa
#00BA38 versicolor
#619CFF virginica
并执行以下操作:Vector<Type> v = new Vector<>()
和v.addElement(f(a))
返回f(a)。这可以实现吗?
答案 0 :(得分:1)
您可以定义界面
public interface Command {
public int myFunction(String param);
}
然后实现接口
public class ImplementedCommand1 implements Command{
@Override
public int myFunction(String param) {
// Your code calculation
return 0;
}
}
public class ImplementedCommand2 implements Command{
@Override
public int myFunction(String param) {
// Your code calculation
return 0;
}
}
最后你使用你的功能
Vector<Command> v = new Vector<>();
v.addElement(new ImplementedCommand1());
v.addElement(new ImplementedCommand2());
Command command1 = v.get(0);
command1.myFunction("Hello");
Command command2 = v.get(1);
command2.myFunction("Hello2");
答案 1 :(得分:0)
您可以拥有如下界面:
public interface MyFunction
{
void doSomething(int a);
}
现在假设您有两个该接口的实现,在调用doSomething时会执行不同的操作。
public class MyCoolFunction implements MyFunction
{
public void doSomething(int a)
{
System.out.println("You passed in " + a);
}
}
public class MyNotSoCoolFunction implements MyFunction
{
public void doSomething(int a)
{
System.out.println("Hello");
}
}
然后你可以像这样列出他们:
List<MyFunction> functions = new ArrayList<>();
functions.add(new MyCoolFunction());
functions.add(new MyNotSoCoolFunction());
答案 2 :(得分:0)
试试这个
Vector<Function<Integer, String>> v = new Vector<>();
v.addElement(a -> "function0 body, arg=" + a);
v.addElement(a -> "function1 body, arg=" + a);
System.out.println(v.get(0).apply(7));
// -> function0 body, arg=7