1

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
Mark
  • 63
  • 7
  • possible duplicate of [Why use generic constraints in C#](http://stackoverflow.com/questions/4073852/why-use-generic-constraints-in-c) – Kirk Woll Jun 15 '11 at 20:03

3 Answers3

3

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

Coeffect
  • 8,772
  • 2
  • 27
  • 42
0

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

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
0

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.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435