为什么 Comparable 和 Comparator 是 Java 中 PECS 通配符类型的消费者

Why Comparable and Comparator are consumers in PECS wildcard types in Java

在EffectiveJava中,在“Use bounded wildcards to increase API flexibility”项中,在讲到PECS(producer-extends,consumer-super)的用法时,作者提到那:

Comparables are always consumers, so you should generally use Comparable<? super T> in preference to Comparable. The same is true of comparators; therefore, you should generally use Comparator<? super T> in preference to Comparator.

我不清楚为什么 Comparables 和 Comparators 被视为消费者。

在讨论 PECS 的主题之一中,What is PECS (Producer Extends Consumer Super)?,消费者通常将集合称为某些通用方法的参数。

而这里的Comparable只是一个接口

任何人都可以分享一些见解吗?谢谢!

…It is not clear to me why Comparables and Comparators are considered consumers.…“

任何时候泛型 class C<T> 的方法成员, 接受 (即 „consumes“) 类型为 T 的参数,则该方法是 T 的消费者s.

所以Comparator<T>.compareTo(T o)被认为是o类型对象的“消费者”由类型变量 T.

表示

当我们说“Comparable是一个消费者”时,我们实际上是指“接口的方法是一个消费者”。这是对“Comparable 只是一个接口”的疑问的回答。

查看其签名:https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Comparable.html#compareTo(T)

int compareTo​(T o)

它使用泛型 T,它不产生任何泛型对象。

接口 Consumer<T> and Supplier<T> 可以做一个很好的类比(Supplier 类似于 Producer)。 Consumer<T> 是接受 T 的函数,而 Supplier<T> 是 return 接受 T 的函数。请注意,我们正在谈论方法签名和 return 类型,我们没有提及方法的语义。这是 PECS 的核心 属性:它独立于语义,可以仅根据所用方法的签名和 return 类型来确定。

查看Comparable<T> and Comparator<T>,我们发现两者都有接收的方法(int compareTo(T)int compare(T, T)),即consumeT的。

对于集合,我们必须查看我们如何使用集合,即如果我们使用生产者或 consumer-methods:

  • 如果我们从集合(T get(int)、迭代器等)中检索数据,列表 会为我们生成 值,我们使用 ? extends T .
  • 如果我们使用集合来存储数据,(即我们调用add(T)addAll(Collection<T>)contains(T)、...),我们调用消费方法,因此该方法是我们数据的 消费者 ,我们使用 ? super T.
  • 如果我们使用集合来存储和检索值,集合同时充当消费者和生产者,因此我们必须使用精确的T, 既不使用 ... extends ... 也不使用 ... super ....