Java 8中的方法参考 [英] Method reference in Java 8

查看:71
本文介绍了Java 8中的方法参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Car {

    private int maxSpeed;

    public Car(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }
}

我们可以对汽车列表进行排序

We can sort a list of cars by,

    Car carX = new Car(155);
    Car carY = new Car(140);

    List<Car> cars = new ArrayList<>();
    cars.add(carX);
    cars.add(carY);

    cars.sort(Comparator.comparing(Car::getMaxSpeed));

如果看到方法Comparator.comparing的签名,则输入参数类型为Function<? super T, ? extends U>

If we see the signature of the method Comparator.comparing, the input parameter type is Function<? super T, ? extends U>

在上面的示例中,如何将Car::getMaxSpeed强制转换为Function<? super T, ? extends U>,而以下内容无法编译?

In the above example, how is Car::getMaxSpeed being cast to Function<? super T, ? extends U> while the following does not compile?

  Function<Void, Integer> function = Car::getMaxSpeed;

推荐答案

这是因为getMaxSpeed方法是Function<Car, Integer>.

即:

<Car, Integer> Comparator<Car> java.util.Comparator.comparing(
    Function<? super Car, ? extends Integer> keyExtractor
)

注意

为了从具有::习惯用法的Car实例引用getMaxSpeed,您必须声明一个具有签名:getMaxSpeed(Car car)Car方法.

In order to reference getMaxSpeed from an instance of Car with the :: idiom, you would have to declare a Car method with signature: getMaxSpeed(Car car).

这篇关于Java 8中的方法参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆