gpt4 book ai didi

java - 比较器比较类型推断

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:56 27 4
gpt4 key购买 nike

假设更改 Comparator.comparing源代码来自

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable) (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<T, U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable) (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}

我们有以下类

class PhysicalObject {
double weight;
public Double getWeight(){
return weight;
}
}
class Car extends PhysicalObject {}

下面的语句不编译

Function<PhysicalObject, Double> weight = p->p.getWeight();

Comparator<Car> c = HypotheticComparators.comparing(weight);

编译时Comparator<Car> c3_1 = HypotheticComparators.comparing(PhysicalObject::getWeight);

我理解第一条语句不能编译是因为修改后的比较函数没有有界通配符(? super T),但为什么第二条语句可以毫无问题地编译?

最佳答案

comparing定义为:

Comparator<T> comparing(Function<T, U> keyExtractor) // abbreviated

声明:

Comparator<Car> c = comparing(weight);

要求参数为 Function<Car, ?> ,但是weightFunction<PhysicalObject, Double>所以你会得到编译错误。

然而,当做

Comparator<Car> c3_1 = comparing(PhysicalObject::getWeight);

Function<Car, ?>方法 ? apply(Car t)Double getWeight() 充分实现父类(super class)的 PhysicalObject , 自 t->getWeight()是对该方法的调用。

PhysicalObject::getWeight方法引用类似于以下 lambda:

Comparator<Car> c3_1 = comparing((Car t) -> {
PhysicalObject p = t;
return p.getWeight(); // call PhysicalObject::getWeight
});

或者下面的匿名类:

Comparator<Car> c3_1 = comparing(new Function<Car, Double>() {
@Override
public Double apply(Car t) {
PhysicalObject p = t;
return p.getWeight();
}
});

来自 Car 的扩大转换至 PhysicalObject允许在方法引用中。

关于java - 比较器比较类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162228/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com