gus*_*ata 1 java generics interface java-11
我正在尝试使用单个方法(当然)在 Java 中创建一个功能接口,该方法可以采用任何类型的参数并返回任何数据类型(即泛型方法)。
这是我到目前为止:
计算器.java
public interface Calculator<T> {
T operation(T n1, T... n2); //this is where the optional parameter comes in
}
Run Code Online (Sandbox Code Playgroud)
主程序
public static void main(String[] args) {
Calculator<Integer> addition = (n1, n2) -> n1 + n2; //this gives an error
}
Run Code Online (Sandbox Code Playgroud)
错误说:
二元运算符“+”的错误操作数类型
public interface Calculator<T> {
T operation(T n1, T .. n2); //this is where the optional parameter comes in
}
Run Code Online (Sandbox Code Playgroud)
错误来自于您试图将运算符+应用于整数和整数数组的事实。例如以下
public interface Calculator<T> {
T operation(T n1, T n2); //this is where the optional parameter comes in
}
Run Code Online (Sandbox Code Playgroud)
会正常工作,因为您会将运算符+应用于两个整数。
如果要保持相同的接口,则需要将主代码更改为:
public static void main(String[] args) {
Calculator<Integer> addition = (n1, n2) -> n1 + Arrays.stream(n2).reduce(0, Integer::sum);
}
Run Code Online (Sandbox Code Playgroud)
是否可以在 Java 中创建带有可选参数的通用功能接口?
从这个SO Thread可以读到:
varargs 可以做到这一点(在某种程度上)。除此之外,必须提供方法声明中的所有变量。如果您希望变量是可选的,您可以使用不需要参数的签名来重载该方法。
话虽如此,你可以做的是:
public interface Calculator<T> {
T operation(T ...n);
}
Run Code Online (Sandbox Code Playgroud)
这样,该方法operation可以接受 0, 1 ... N 个元素甚至null.
然后在你的主要:
Calculator<Integer> addition = n -> (n == null) ? 0 :
Arrays.stream(n).reduce(0, Integer::sum);
Run Code Online (Sandbox Code Playgroud)
一个正在运行的例子:
public class Main {
public static void main(String[] args) {
Calculator<Integer> addition = n -> (n == null) ? 0 : Arrays.stream(n).reduce(0, Integer::sum);
System.out.println(addition.operation(1, 2));
System.out.println(addition.operation(1));
System.out.println(addition.operation());
System.out.println(addition.operation(null));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
3 // 1 + 2
1 // 1
0 // empty array
0 // null
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |