Java 8 Comparator比较静态函数

时间:2018-03-06 06:06:48

标签: java generics bounded-wildcard

对于Comparator类中的比较源代码

    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));
    }

我理解superextends之间的区别。我不明白的是,为什么这种方法有它们。有人可以举例说明当参数看起来像Function<T, U> keyExtractor时无法实现的内容吗?

例如:

Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);

也可以使用以下函数定义进行编译

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));
}

2 个答案:

答案 0 :(得分:8)

这是一个简单的例子:按重量比较汽车。我将首先以文本形式描述问题,然后展示如果省略? extends? super,它可能出错的每种可能方式。我还展示了在每种情况下都可用的丑陋的部分解决方法。 如果您更喜欢代码而不是散文,请直接跳到第二部分,它应该是不言自明的。

对问题的非正式讨论

首先,逆变? super T

假设您有CarPhysicalObject两个类,Car extends PhysicalObject。现在假设您有一个扩展Weight的函数Function<PhysicalObject, Double>

如果声明为Function<T,U>,则您无法重复使用Weight extends Function<PhysicalObject, Double>函数来比较两辆汽车,因为Function<PhysicalObject, Double>不符合Function<Car, Double>。但你显然想要能够按重量比较汽车。因此,逆变? super T是有意义的,因此Function<PhysicalObject, Double>符合Function<? super Car, Double>

现在是协变? extends U声明。

假设您有RealPositiveReal两个类PositiveReal extends Real,并且假设RealComparable

假设前一个示例中的函数Weight实际上具有稍微更精确的类型Weight extends Function<PhysicalObject, PositiveReal>。如果keyExtractor的声明为Function<? super T, U>而不是Function<? super T, ? extends U>,则您无法利用PositiveReal也是Real的事实,因此,两个PositiveReal无法相互比较,即使它们实现Comparable<Real>,也没有不必要的限制Comparable<PositiveReal>

总结:通过声明Function<? super T, ? extends U>Weight extends Function<PhysicalObject, PositiveReal>可以替换Function<? super Car, ? extends Real>使用Car来比较Comparable<Real>

我希望这个简单的例子澄清为什么这样的声明是有用的。

代码:省略? extends? super时的后果的完整列举

这是一个可编辑的示例,如果我们省略? super? extends,系统列举所有可能出错的事情。此外,还显示了两个(丑陋的)部分解决方法。

import java.util.function.Function;
import java.util.Comparator;

class HypotheticComparators {

  public static <A, B> Comparator<A> badCompare1(Function<A, B> f, Comparator<B> cb) {
    return (A a1, A a2) -> cb.compare(f.apply(a1), f.apply(a2));
  }

  public static <A, B> Comparator<A> badCompare2(Function<? super A, B> f, Comparator<B> cb) {
    return (A a1, A a2) -> cb.compare(f.apply(a1), f.apply(a2));
  }

  public static <A, B> Comparator<A> badCompare3(Function<A, ? extends B> f, Comparator<B> cb) {
    return (A a1, A a2) -> cb.compare(f.apply(a1), f.apply(a2));
  }

  public static <A, B> Comparator<A> goodCompare(Function<? super A, ? extends B> f, Comparator<B> cb) {
    return (A a1, A a2) -> cb.compare(f.apply(a1), f.apply(a2));
  }

  public static void main(String[] args) {

    class PhysicalObject { double weight; }
    class Car extends PhysicalObject {}
    class Real { 
      private final double value; 
      Real(double r) {
        this.value = r;
      }
      double getValue() {
        return value;
      }
    }
    class PositiveReal extends Real {
      PositiveReal(double r) {
        super(r);
        assert(r > 0.0);
      }
    }

    Comparator<Real> realComparator = (Real r1, Real r2) -> {
      double v1 = r1.getValue();
      double v2 = r2.getValue();
      return v1 < v2 ? 1 : v1 > v2 ? -1 : 0;
    };
    Function<PhysicalObject, PositiveReal> weight = p -> new PositiveReal(p.weight);

    // bad "weight"-function that cannot guarantee that the outputs 
    // are positive
    Function<PhysicalObject, Real> surrealWeight = p -> new Real(p.weight);

    // bad weight function that works only on cars
    // Note: the implementation contains nothing car-specific,
    // it would be the same for every other physical object!
    // That means: code duplication!
    Function<Car, PositiveReal> carWeight = p -> new PositiveReal(p.weight); 

    // Example 1
    // badCompare1(weight, realComparator); // doesn't compile
    // 
    // type error:
    // required: Function<A,B>,Comparator<B>
    // found: Function<PhysicalObject,PositiveReal>,Comparator<Real>

    // Example 2.1
    // Comparator<Car> c2 = badCompare2(weight, realComparator); // doesn't compile
    // 
    // type error:    
    // required: Function<? super A,B>,Comparator<B>
    // found: Function<PhysicalObject,PositiveReal>,Comparator<Real>

    // Example 2.2
    // This compiles, but for this to work, we had to loosen the output
    // type of `weight` to a non-necessarily-positive real number
    Comparator<Car> c2_2 = badCompare2(surrealWeight, realComparator);

    // Example 3.1
    // This doesn't compile, because `Car` is not *exactly* a `PhysicalObject`:
    // Comparator<Car> c3_1 = badCompare3(weight, realComparator); 
    // 
    // incompatible types: inferred type does not conform to equality constraint(s)
    // inferred: Car
    // equality constraints(s): Car,PhysicalObject

    // Example 3.2
    // This works, but with a bad code-duplicated `carWeight` instead of `weight`
    Comparator<Car> c3_2 = badCompare3(carWeight, realComparator);

    // Example 4
    // That's how it's supposed to work: compare cars by their weights. Done!
    Comparator<Car> goodComparator = goodCompare(weight, realComparator);

  }
}

相关链接

  1. Scala中定义 - 站点协方差和逆变的详细说明:How to check covariant and contravariant position of an element in the function?

答案 1 :(得分:3)

比方说,我们想用他们使用的飞机来比较商业航班。因此,我们需要一种接收飞行并返回飞机的方法:

Plane func (CommercialFlight)

当然,这是一个Function<CommercialFlight, Plane>

现在,重要的是该函数返回Plane。什么样的飞机返回并不重要。所以这样的方法也应该有效:

CivilianPlane func (CommercialFlight)

现在技术上这是Function<CommercialFlight, CivilianPlane>,它与Function<CommercialFlight, Plane>. So without the extends`不同,不允许使用此功能。

同样,另一个重要的是可以接受CommercialFlight作为参数。所以这样的方法也应该有效:

Plane func (Flight)

从技术上讲,这是Function<Flight, Plane>,也与Function<CommercialFlight, Plane>不同。因此,如果没有super,也不允许使用此函数。