Java 8 中的方法参考
2022-09-04 00:44:27
public class Car {
private int maxSpeed;
public Car(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public int getMaxSpeed() {
return maxSpeed;
}
}
我们可以按以下条件对汽车列表进行排序:
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>
在上面的示例中,当以下内容未编译时,如何被强制转换为?Car::getMaxSpeed
Function<? super T, ? extends U>
Function<Void, Integer> function = Car::getMaxSpeed;