[英]In Java, how do I create a List of function pointers which take an argument each?
I've already looked here , that works for an argument less method list containing Runnables. 我已经看过这里了 ,它适用于包含Runnables的无参数方法列表。 I need to have
Consumer
in my case. 我需要拥有
Consumer
。 This is what I have so far: 这是我到目前为止的内容:
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.function.Consumer;
public class experiment {
private static List<Consumer<String>> activities;
public experiment (){
activities = ImmutableList.of(
(userId) -> this::bar, // throws error
(userId) -> this::foo);
}
public void bar(String x) {
System.out.println(x);
}
public void foo(String x) {
System.out.println(x);
}
public static void main(String []args) {
for (int i=0; i<2; i++) {
activities.get(i).accept("activity #" + i);
}
}
}
The error I see is void is not a functional interface
. 我看到的错误是
void is not a functional interface
。
I don't understand why I'm getting that, both bar
and foo
implement the accept method of the Consumer interface. 我不明白为什么会这样,
bar
和foo
实现了Consumer接口的accept方法。 Is there something I'm overlooking here? 我在这里俯瞰什么?
I believe you want to write ImmutableList.of(this::bar, this::foo)
instead of ImmutableList.of((userId) -> this::bar, (userId) -> this::foo)
. 我相信你想写
ImmutableList.of(this::bar, this::foo)
而不是ImmutableList.of((userId) -> this::bar, (userId) -> this::foo)
。
If you do want to use lambdas instead of method references, you should instead write ImmutableList.of((userId) -> this.bar(userId), (userId) -> this.foo(userId))
. 如果确实要使用lambda而不是方法引用,则应该编写
ImmutableList.of((userId) -> this.bar(userId), (userId) -> this.foo(userId))
。
Your lambda's are wrong. 你的lambda错了。 You either supply a method reference, or you supply a lambda expression.
您可以提供方法参考, 也可以提供lambda表达式。 You're trying an incorrect combo.
您正在尝试使用错误的组合。
Also, your two methods foo()
and bar()
should be static
, and your instance variable should not be. 另外,您的两个方法
foo()
和bar()
应该是static
,而您的实例变量应该不是。 To show how instance methods could be called, I've added baz()
and qux()
. 为了展示如何调用实例方法,我添加了
baz()
和qux()
。
Here's showing full example: 这里显示了完整的示例:
public class Experiment {
private List<Consumer<String>> activities;
public Experiment() {
this.activities = ImmutableList.of(
(userId) -> Experiment.bar(userId),
Experiment::foo,
(userId) -> this.baz(userId),
this::qux
);
}
public static void bar(String x) {
System.out.println(x);
}
public static void foo(String x) {
System.out.println(x);
}
public void baz(String x) {
System.out.println(this.hashCode() + ": " + x);
}
public void qux(String x) {
System.out.println(this.hashCode() + ": " + x);
}
public static void main(String[] args) {
Experiment ex = new Experiment();
for (int i = 0; i < ex.activities.size(); i++) {
ex.activities.get(i).accept("activity #" + i);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.