首页 > 解决方案 > Java:优先队列> 比较器和实现

问题描述

我有一个名为 Event 的对象。我曾经将这些事件保存到:

Queue<Event> Q = new PriorityQueue<>(new EventCompare());

但现在我发现如果我有集合队列会更好:

Queue<Set<Event>> Q = new PriorityQueue<>(new EventCompare());

在我的比较器中,我比较事件的值。

private class EventCompare implements Comparator<Event> {
    @Override
    public int compare(Event e1, Event e2) {
        if(e1.getValue() > e2.getValue()) {
            return 1;
        }
        else if(e1.getValue() < e2.getValue()) {
            return -1;
        }


        return 0;
    }
}

现在我希望如果两个值相等,则在同一个集合中。所以队列应该是这样的:

{Event(1)}, {Event(12)}, {Event(15), Event(15)}.

我希望我已经足够清楚了。任何帮助,将不胜感激。

标签: javasetcomparatorpriority-queue

解决方案


推荐阅读