Adding a non-comparable object to a PriorityQueue [closed]

孤街醉人 提交于 2019-12-13 10:53:22

问题


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, which is explicitly non-comparable, is added to a PriorityQueue. As expected per PriorityQueue.add Javadoc, this code throws a ClassCastException because the object is not comparable.

However, it seems that the size of the queue is still increased, although an exception was thrown.

I would have expected both print statements to output 0 but the second one actually outputs 1, as if an object had been added to the queue.

What is happening here?


回答1:


I would not expect an exception to be thrown at all on that line. Read the docs more closely: an exception may be thrown

if the specified element cannot be compared with elements currently in this priority queue according to the priority queue's ordering

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




回答2:


This is the actual statement in the documentation:

A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).

Doing something to the queue that isn't permitted implies no guarantees on how the queue is going to behave when it is done nevertheless. As an additional confirmation, look carefully at this part: "doing so may result in a ClassCastException." In other words, the implementation isn't even required to throw the exception.




回答3:


You claim that an exception is thrown by add(), but your test does not prove that claim. If in fact an exception were thrown, then you should expect the queue's size to remain 0. HOWEVER, you should not expect an exception to be thrown.

The docs for PriorityQueue.add() say:

ClassCastException - if the specified element cannot be compared with elements currently in this priority queue according to the priority queue's ordering

If there are no other elements, then that case does not arise. If you attempted to add another element, however, then an exception should be thrown, and the queue's size should remain 1.



来源:https://stackoverflow.com/questions/32318500/adding-a-non-comparable-object-to-a-priorityqueue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!