gpt4 book ai didi

Java:非空方法作为映射值

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:40:54 24 4
gpt4 key购买 nike

我有这样的代码:

public class A {
private final Map<String, Runnable> map = new HashMap<>();
public A() {
map.put("a", () -> a());
map.put("b", () -> b());
}
public int a() {
return 1;
}
public int b() {
return 2;
}
public int c(String s) {
// map.get(s).run(); <= returns void, but
// I need the result of the
// function paired to the string.
// What TODO?
}
}

我有非空函数(a()b())作为映射的值,与字符串配对。我需要运行函数并获取函数的结果,然后在函数 c() 中返回它。 run() 函数返回 void,因此我无法从中获取值。有什么办法吗?

最佳答案

你想在这里做的是返回一个 int方法的值(value)。为此,您不能使用 Runnable作为run()不返回值。

但是你可以使用 IntSupplier ,这是一个功能接口(interface),表示提供 int 的功能值(value)。其功能方法 getAsInt 用于返回值。

public class A {
private final Map<String, IntSupplier> map = new HashMap<>();
public A() {
map.put("a", () -> a()); // or use the method-reference this::a
map.put("b", () -> b()); // or use the method-reference this::b
}
public int a() {
return 1;
}
public int b() {
return 2;
}
public int c(String s) {
return map.get(s).getAsInt();
}
}

此外,如果您不想返回一个原始对象而是一个对象 MyObject , 您可以使用 Supplier<MyObject> 功能接口(interface)(或 Callable<MyObject> ,如果要调用的方法可以抛出已检查的异常)。

关于Java:非空方法作为映射值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38741632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com