开发者

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. The header of this class is:

public class PriorityQueue<T extends Comparable&开发者_运维百科lt;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.


This means that the T type should have a compareTo method that you can use to sort with. 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.

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


this allows the PriorityQueue to use T.compareTo(T) instead of needing to rely on a supplied Comparator<T> object


All that does is to require that the elements, of type T, be comparable with other objects of the same type (Comparable<T>). The reason that that's used instead of Comparable<?> is that the latter simply says comparable with some type.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜