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;
Comparator.comparingInt
来避免装箱。 - TunakicarX::getMaxSpeed
,这与Car::getMaxSpeed
非常不同。大多数答案都涉及到第一版而非所有版本,这一点很令人困惑:您的编辑使得部分答案无效了... - TunakiVoid
的参数,即期望一个java.lang.Void
实例,但你不太可能看到除了null
之外的其他东西,所以它没有太多用处。关键是,Void
不是void
的包装类型,它只是Void.TYPE
的占位符,后者持有代表void.class
的Class
对象。 - Holger