简体   繁体   中英

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

这允许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> ). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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