使用Lambdas和Generics

Kno*_*uch 2 java java-8

我正在学习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)

我的问题很少

  1. 我的lambdas被定义了两次(x, y) -> x + y.是否可以只定义一次.

  2. 似乎每次运行此代码时,它都会将10封装到Integer,然后运行代码.是否有可能我可以定义此int而不是Integer.我尝试过,new LambdaTest<int>但它没有用.

JB *_*zet 6

  1. 不,一种是类型BiFunction<Integer, Integer, Integer>,而另一种是类型BiFunction<Double, Double, Double>.因此它们彼此不相容.
  2. 要避免拆箱和装箱,您必须使用DoubleBinaryOperator和IntBinaryOperator,它们使用基本类型.但是那时你需要两个不同的接口.


Tun*_*aki 5

  1. 不,这是不可能的,因为lambda实际上是不同的.在第一个,两个xy的类型的Integer,而在第二个,两个xy的类型的Double.不幸的是,Integer并且Double两者都是Number并且+操作没有定义为一般Number.

  2. 也不可能使用具有泛型的原始类型.但是,您可以使用IntBinaryOperator:这是一个在两个int值上运行并返回int值的功能接口.