将不可比较的对象添加到 PriorityQueue [英] Adding a non-comparable object to a PriorityQueue

查看:92
本文介绍了将不可比较的对象添加到 PriorityQueue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

在这段代码中,一个明确不可比较的对象被添加到一个PriorityQueue.正如 PriorityQueue 所预期的那样.添加 Javadoc,这段代码抛出一个ClassCastException,因为对象是不可比较的.

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.

我原以为两个打印语句都输出 0,但第二个语句实际上输出 1,就好像一个对象已添加到队列中一样.

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.

这里发生了什么?

推荐答案

我不希望在该行上抛出异常.更仔细地阅读文档:可能会抛出异常

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.

这篇关于将不可比较的对象添加到 PriorityQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆