我正在学习Java 8,我正在尝试使用lambdas和泛型,我写了这个小例子
import java.util.function.*;
public class LambdaTest<T> {
public T calculate(T x, T y, BiFunction<T, T, T> func) {
return func.apply(x, y);
}
public static void main(String args[]) {
LambdaTest<Integer> l = new LambdaTest<Integer>();
System.out.println("" + l.calculate(10, 10, (x, y) -> x + y));
System.out.println("" + l.calculate(10, 10, (x, y) -> x * y));
System.out.println("" + l.calculate(10, 10, (x, y) -> x / y));
System.out.println("" + l.calculate(10, 10, (x, y) -> x - y));
LambdaTest<Double> l2 = new LambdaTest<Double>();
System.out.println("" + l2.calculate(10.0, 10.0, (x, y) -> x + y));
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题很少
我的lambdas被定义了两次(x, y) -> x + y.是否可以只定义一次.
似乎每次运行此代码时,它都会将10封装到Integer,然后运行代码.是否有可能我可以定义此int而不是Integer.我尝试过,new LambdaTest<int>但它没有用.
BiFunction<Integer, Integer, Integer>,而另一种是类型BiFunction<Double, Double, Double>.因此它们彼此不相容.不,这是不可能的,因为lambda实际上是不同的.在第一个,两个x和y的类型的Integer,而在第二个,两个x和y的类型的Double.不幸的是,Integer并且Double两者都是Number并且+操作没有定义为一般Number.
也不可能使用具有泛型的原始类型.但是,您可以使用IntBinaryOperator:这是一个在两个int值上运行并返回int值的功能接口.
| 归档时间: |
|
| 查看次数: |
134 次 |
| 最近记录: |