Firstly can anyone explain why the following code fails? It compiles OK but when I run it, it fails on the second attempt to add something with...
Exception in thread "main" java.lang.ClassCastException: CD at java.util.PriorityQueue.fixUp(Unknown Source) at java.util.PriorityQueue.offer(Unknown Source) at TestCD.main(CD3.java:54)
If I create the PriorityQueue using a Comparator then it works okay. Is it something to do with the PriorityQueue being unable to perform any ordering on the set because there is no defined "natural order"?
My other question is - on a PriorityQueue - what is the difference between add() and offer() - are they interchangeable?
The answer to the first question is that when you do not create the PriorityQueue with a Comparator, the elements that you add to the queue must be mutually Comparable.
This means that you need to modify your class definition to implement Comparable.
The answer to the second question is from the API docs for the Queue interface.
boolean offer(E o)
Inserts the specified element into this queue, if possible. When using queues that may impose insertion restrictions (for example capacity bounds), method offer is generally preferable to method Collection.add(E), which can fail to insert an element only by throwing an exception.
Parameters: o - the element to insert. Returns: true if it was possible to add the element to this queue, else false