如何使用 PriorityQueue? [英] How do I use a PriorityQueue?

查看:30
本文介绍了如何使用 PriorityQueue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得 PriorityQueue 对我希望它排序的内容进行排序?

How do I get a PriorityQueue to sort on what I want it to sort on?

另外,offeradd 方法?

Also, is there a difference between the offer and add methods?

推荐答案

使用带有 Comparator比较器 并传入一个比较器,该比较器以适合您的排序顺序的方式进行比较.如果您举例说明要如何排序,如果您不确定,我们可以提供一些示例代码来实现比较器.(虽然很简单.)

Use the constructor overload which takes a Comparator<? super E> comparator and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you're not sure. (It's pretty straightforward though.)

正如其他地方所说:offeradd 只是不同的接口方法实现.在我得到的 JDK 源代码中,add 调用 offer.尽管 addoffer 通常具有潜在不同的行为,因为 offer 能够表明该值可以'由于大小限制未添加,此差异与无界 PriorityQueue 无关.

As has been said elsewhere: offer and add are just different interface method implementations. In the JDK source I've got, add calls offer. Although add and offer have potentially different behaviour in general due to the ability for offer to indicate that the value can't be added due to size limitations, this difference is irrelevant in PriorityQueue which is unbounded.

以下是按字符串长度排序的优先级队列示例:

Here's an example of a priority queue sorting by string length:

// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;

public class Test {
    public static void main(String[] args) {
        Comparator<String> comparator = new StringLengthComparator();
        PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
        queue.add("short");
        queue.add("very long indeed");
        queue.add("medium");
        while (queue.size() != 0) {
            System.out.println(queue.remove());
        }
    }
}

// StringLengthComparator.java
import java.util.Comparator;

public class StringLengthComparator implements Comparator<String> {
    @Override
    public int compare(String x, String y) {
        // Assume neither string is null. Real code should
        // probably be more robust
        // You could also just return x.length() - y.length(),
        // which would be more efficient.
        if (x.length() < y.length()) {
            return -1;
        }
        if (x.length() > y.length()) {
            return 1;
        }
        return 0;
    }
}

这是输出:

中等

确实很长

这篇关于如何使用 PriorityQueue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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