Adding a disparate object to a PriorityQueue

Consider the following code:

import java.util.PriorityQueue; public class Test { public static void main(String argv[]) { PriorityQueue<A> queue = new PriorityQueue<>(); System.out.println("Size of queue is " + queue.size()); // prints 0 try { queue.add(new A()); } catch (ClassCastException ignored) { } System.out.println("Size of queue is " + queue.size()); // prints 1 } } class A { } // non-comparable object 

In this code, an object that is clearly not comparable is added to the PriorityQueue . As expected in the PriorityQueue.add Javadoc, this code throws a ClassCastException because the object is not comparable.

However, it seems the queue size is still increasing, although an exception has been thrown.

I would expect both print statements to print 0, and the second actually prints 1, as if the object was added to the queue.

What's going on here?

-2
source share
3 answers

I would not expect an exception to be thrown at all on this line. Read the documents more carefully: an exception can be thrown

if the specified element cannot be compared with the elements in this priority queue, in accordance with the priority order

Since there are no other elements in the priority queue, I would not expect an exception to be thrown.

+4
source

This is the actual statement in the documentation:

A priority ordering based on natural ordering also prevents the insertion of disparate objects (this may lead to a ClassCastException ).

Running something in a queue that is not allowed does not imply any guarantees as to how the queue will behave when it is completed. As an additional confirmation, take a good look at this part: β€œit may lead to a ClassCastException ”. In other words, an implementation is not required even for an exception.

+4
source

You claim that an exception was thrown by add() , but your test does not prove this claim. If the exception was actually thrown, you should expect the queue size to remain 0. HOWEVER, you should not expect the exception to be thrown.

The docs for PriorityQueue.add() say:

ClassCastException - if the specified element cannot be compared with the elements in this priority queue, in accordance with the priority order

If there are no other elements, then this case does not arise. However, if you tried to add another element, then an exception should be thrown, and the queue size should remain 1.

+2
source

All Articles