Java泛型:Collections.max()签名和比较器 [英] Java generics: Collections.max() signature and Comparator

查看:477
本文介绍了Java泛型:Collections.max()签名和比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解取放原则集合:如果一个方法接受一个集合,它将写入一个类型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>(它们将以某种方式从中检索),?应该使用扩展T ,因为 T 的子类的任何实例也都是 T



传递给方法的参数化类型将消耗 T (他们会传递给它做一些事情),?应该使用超级T ,因为可以合法地将 T 的一个实例传递给任何接受一些超类型 T 。例如,可以在集合<整数> 上使用比较器< Number> ?由于 Comparator< Integer> 无法在集合<数字>

编辑:
澄清更多关于get / put(produce / consume)的信息:

  public T something(); 
$

以上是一个产生 T

  public void something(T t); 
$

以上是一个消耗 T < code $。
$ b

Producer extends ,Consumer super 适用于传递参数化对象的方法将如何使用该对象。在 Collections.max()的情况下,将从集合中检索项目,因此它是生产者。这些项目将作为参数传递给比较器上的方法,因此它是一个消费者。


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> ?

解决方案

Josh Bloch's mnemonic PECS is useful here. It stands for:

Producer extends, Consumer super

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 of T is also a T.

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 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>.

Edit: To clarify a little more on get/put (produce/consume):

public T something();
       ^

The above is a method that produces T.

public void something(T t);
                      ^

The above is a method that consumes T.

"Producer 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.

这篇关于Java泛型:Collections.max()签名和比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆