2

Why is PriorityQueue in Java defined as,

PriorityQueue<T>

and not as,

PriorityQueue<T extends Comparable<? super T>

It rather gives a ClassCastException at runtime if do not queue objects of type Comparable. (and if I am not using a custom Comparator).

Why not catch it at compile time?

vikky.rk
  • 3,989
  • 5
  • 29
  • 32
  • 3
    related: [Creating a TreeSet with a non-Comparable class: why a run-time exception, rather than compile-time error?](http://stackoverflow.com/questions/13890542/creating-a-treeset-with-a-non-comparable-class-why-a-run-time-exception-rather) – Paul Bellora Feb 21 '13 at 02:13

1 Answers1

5

It's done so that you can still use the priority queue for Objects that do not implement the Comparable interface. In such cases you just supply your own custom comparator and everything just works.

This increases the usability of the class, at minimal to no cost. This behavior is well-documented in the Javadoc.

Perception
  • 79,279
  • 19
  • 185
  • 195