Java泛型:Collections.max()签名和比较器 [英] Java generics: Collections.max() signature and Comparator
问题描述
我了解取放原则集合:如果一个方法接受一个集合,它将写入一个类型T to,参数必须是 Collection <? super T>
,而如果它将读取类型T from,参数必须是 Collection <?扩展T>
。
但是有人可以解释 Collections.max()
签名:
public static< T> T max(Collection<?extends T> coll,
Comparator< super T> comp)
<特别是为什么它是比较器<? super T>
而不是比较器<?延伸T>
?
Josh Bloch的助记符 PECS 。它表示:
生产者延伸
,消费者超级
这意味着当传递给方法的参数化类型将产生 T $ c $ 的实例 c>(它们将以某种方式从中检索),
?应该使用扩展T
,因为 T
的子类的任何实例也都是 T
。
传递给方法的参数化类型将消耗 编辑: 以上是一个产生 以上是一个消耗 Producer 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 But could someone please explain the In particular why is it Josh Bloch's mnemonic PECS is useful here. It stands for: Producer This means that when a parameterized type being passed to a method will produce instances of When a parameterized type being passed to a method will consume instances of Edit:
To clarify a little more on get/put (produce/consume): The above is a method that produces The above is a method that consumes "Producer 这篇关于Java泛型:Collections.max()签名和比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! T
(他们会传递给它做一些事情),?应该使用超级T
,因为可以合法地将 T
的一个实例传递给任何接受一些超类型 T
。例如,可以在集合<整数>
上使用比较器< Number>
。 ?由于
Comparator< Integer>
无法在集合<数字> $上操作,所以扩展T
澄清更多关于get / put(produce / consume)的信息:
public T something();
$
T
。
public void something(T t);
$
T < code $。
$ b extends
,Consumer super
适用于传递参数化对象的方法将如何使用该对象。在 Collections.max()
的情况下,将从集合
中检索项目,因此它是生产者。这些项目将作为参数传递给比较器
上的方法,因此它是一个消费者。Collection<? super T>
, whereas if it will read a type T from, the parameter has to be Collection<? extends T>
.Collections.max()
signature:public static <T> T max(Collection<? extends T> coll,
Comparator<? super T> comp)
Comparator<? super T>
instead of Comparator<? extends T>
?extends
, Consumer super
T
(they will be retrieved from it in some way), ? extends T
should be used, since any instance of a subclass of T
is also a T
.T
(they will be passed to it to do something), ? super T
should be used because an instance of T
can legally be passed to any method that accepts some supertype of T
. A Comparator<Number>
could be used on a Collection<Integer>
, for example. ? extends T
would not work, because a Comparator<Integer>
could not operate on a Collection<Number>
.public T something();
^
T
.public void something(T t);
^
T
.extends
, Consumer super
" applies to how the method a parameterized object is being passed to is going to be using that object. In the case of Collections.max()
, items will be retrieved from the Collection
, so it is a producer. Those items will be passed as arguments to the method on Comparator
, so it is a consumer.