Java 泛型:Collections.max() 签名和比较器
我理解集合的获取和放置原则:如果方法接受一个集合,并将类型 T 写入其中,参数必须是 Collection
,而如果要从中读取类型 T,则参数必须是 Collection
。
但有人可以解释一下 Collections.max()
签名:
public static <T> T max(Collection<? extends T> coll,
Comparator<? super T> comp)
特别是为什么是 Comparator<? super T>
而不是 Comparator
?
I understand the get and put principle for collections: if a method takes in a collection that it will write a type T to, the parameter has to be Collection<? super T>
, whereas if it will read a type T from, the parameter has to be Collection<? extends T>
.
But could someone please explain the Collections.max()
signature:
public static <T> T max(Collection<? extends T> coll,
Comparator<? super T> comp)
In particular why is it Comparator<? super T>
instead of Comparator<? extends T>
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Josh Bloch 的助记符 PECS 在这里很有用。它代表:
生产者
extends
,消费者super
这意味着当参数化类型传递给方法时将产生
T 的实例
(它们将以某种方式从中检索),?应该使用 extends T
,因为T
子类的任何实例也是T
。当传递给方法的参数化类型将消耗
T
实例(它们将被传递给它来执行某些操作)时,?应该使用 super T
,因为T
的实例可以合法地传递给任何接受T
超类型的方法。例如,Comparator
可以用在Collection
上。 <代码>? extends T 不起作用,因为Comparator
无法对Collection
进行操作。编辑:
进一步澄清一下 get/put(生产/消费):
上面是一个生成
T
的方法。上面是一个消耗
T
的方法。“生产者
extends
,消费者super
”适用于传递参数化对象的方法将如何使用该对象。对于Collections.max()
,将从Collection
中检索项目,因此它是一个生产者。这些项目将作为参数传递给 Comparator 上的方法,因此它是一个消费者。Josh Bloch's mnemonic PECS is useful here. It stands for:
Producer
extends
, Consumersuper
This means that when a parameterized type being passed to a method will produce instances of
T
(they will be retrieved from it in some way),? extends T
should be used, since any instance of a subclass ofT
is also aT
.When a parameterized type being passed to a method will consume instances of
T
(they will be passed to it to do something),? super T
should be used because an instance ofT
can legally be passed to any method that accepts some supertype ofT
. AComparator<Number>
could be used on aCollection<Integer>
, for example.? extends T
would not work, because aComparator<Integer>
could not operate on aCollection<Number>
.Edit:
To clarify a little more on get/put (produce/consume):
The above is a method that produces
T
.The above is a method that consumes
T
."Producer
extends
, Consumersuper
" applies to how the method a parameterized object is being passed to is going to be using that object. In the case ofCollections.max()
, items will be retrieved from theCollection
, so it is a producer. Those items will be passed as arguments to the method onComparator
, so it is a consumer.比较器消耗一对 T 并生成一个 int。 Collection 生成比较器消耗的 T。
超级消费,延伸生产。
就获取和放置原则而言,获取产生而放置消耗。
The Comparator consumes a pair of Ts and produces an int. The Collection produces the Ts the comparator consumes.
Super consumes, extends produces.
In relation to the get and put principle, get produces and put consumes.
比较器需要能够采用
T
作为参数。The comparator needs to be able to take a
T
as an argument.