简体   繁体   English

公共类PriorityQueue <T extends Comparable<T> &gt;

[英]public class PriorityQueue <T extends Comparable<T>>

I am having some difficulty in being able to come up with an answer to the following question. 我在提出以下问题的答案时遇到了一些困难。 I was able to know that it uses Generics and known that it would help it help to remove some run time errors with the type, but am unable to think of answer to write for it. 我能够知道它使用了泛型,并且知道它将有助于消除该类型的某些运行时错误,但无法想到为它编写答案。

A Java class is to be used to store the elements of a priority queue, which will be sorted into priority order. 将使用Java类来存储优先级队列的元素,这些元素将按优先级排序。 The header of this class is: 该类的头是:

public class PriorityQueue<T extends Comparable<T>> 

Explain the significance of <T extends Comparable<T>> both for code in the implementation of Priority Queue, and for client code that creates an instance of Priority Queue. 解释<T extends Comparable<T>>的意义,既适用于实现Priority Queue的代码,也适用于创建Priority Queue实例的客户端代码。

This means that the T type should have a compareTo method that you can use to sort with. 这意味着T类型应该具有可以用于排序的compareTo方法。 It means that you don't have to find a way to hard code the sorting; 这意味着您不必寻找一种方法来对分类进行硬编码。 any type T with a suitable comparison method will work. 任何具有合适比较方法的T型都可以使用。

For reference: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Comparable.html 供参考: http : //download.oracle.com/javase/1.4.2/docs/api/java/lang/Comparable.html

这允许PriorityQueue使用T.compareTo(T)而不是依赖于提供的Comparator<T>对象

All that does is to require that the elements, of type T , be comparable with other objects of the same type ( Comparable<T> ). 所有要做的就是要求类型T的元素必须与相同类型的其他对象( Comparable<T> )相比较。 The reason that that's used instead of Comparable<?> is that the latter simply says comparable with some type . 之所以使用它而不是Comparable<?>是后者只是说与某种类型可比。

But since the priority queue holds objects of type T only, and thus compares other objects of type T only, it's fair to require that T be comparable with other objects of the same type. 但是,由于优先级队列仅保存类型T对象,因此仅比较类型T其他对象,因此公平地要求T必须与相同类型的其他对象可比。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM