首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >维护对的PriorityQueue,以便根据对类的两个字段对其元素进行排序

维护对的PriorityQueue,以便根据对类的两个字段对其元素进行排序
EN

Stack Overflow用户
提问于 2021-06-07 12:02:54
回答 1查看 214关注 0票数 1

我有两个X&Y数组,我将从中创建对Xi & Yi。现在,我想将它们添加到priorityQueue中,以便检索队列中当前可用的最大对。从最大我指的是最大'X‘的对,如果存在多个相等的较大的'X',那么优先考虑'Y’。到目前为止,我已经尝试了三种方法,但它们都没有奏效。

代码语言:javascript
复制
// 1] Using Lambda Operator
public static void main(String[] args)
{
    PriorityQueue<Pair> pTq = new PriorityQueue<>((x, y) -> (x.X == y.X) ? x.Y-y.Y : x.X-y.X);
    int[] X = {1, 6, 4, 9, 13, 13, 5, 20, 7, 6};
    int[] Y = {2, 9, 13, 4, 8, 1, 16, 7, 5, 5};
    for (int i=0; i<10; i++)
        pTq.add(new Pair(X[i] , Y[i]));
    System.out.println( pTq );
}
代码语言:javascript
复制
// 2] Using Custom Comparator
public static void main(String[] args)
{
    PriorityQueue<Pair> pTq = new PriorityQueue<Pair>(Comparator.comparing(Pair::getX).thenComparing(Pair::getY));

    int[] X = {1, 6, 4, 9, 13, 13, 5, 20, 7, 6};
    int[] Y = {2, 9, 13, 4, 8, 1, 16, 7, 5, 5};
    for (int i=0; i<10; i++)
        pTq.add(new Pair(X[i] , Y[i]));
    System.out.println( pTq );
}
代码语言:javascript
复制
// 3] Again Custom Comparator
public static void main(String[] args)
{
    PriorityQueue<Pair> pTq = new PriorityQueue<>(new Comparator<Pair>()
    {
        @Override
        public int compare(Pair a, Pair b)
        {
            return (a.X == b.X) ? a.Y-b.Y : a.X-b.X;
        }
    });
    int[] X = {1, 6, 4, 9, 13, 13, 5, 20, 7, 6};
    int[] Y = {2, 9, 13, 4, 8, 1, 16, 7, 5, 5};
    for (int i=0; i<10; i++)
        pTq.add(new Pair(X[i] , Y[i]));
    System.out.println( pTq );
}
代码语言:javascript
复制
// Pair Class for all of the above
class Pair
{
    int X, Y;
    Pair (int x, int y)
    {
        X = x;
        Y = y;
    }
    int getX(){return X;}
    int getY(){return Y;}
    public String toString()
    {
        return ("("+X+" , "+Y+")");
    }
}

预期结果:(1,2),(4,13),(5,16),(6,5),(6,9),(7,5),(9,4),(13,1),(13,8),(20,7)实际结果:(1,2),(6,5),(4,13),(7,5),(6,9),(13,1),(5,16),(20,7),(9,4),(13,8)

我知道我想在这里实现什么,可以使用其他的数据结构,比如带有自定义比较器的对的列表,但是我想知道这里的错误是什么,或者我在这里遗漏了什么。谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-07 12:07:23

优先级队列的元素已经按正确的顺序排列。您被打印的顺序误导了--参见PriorityQueue.toString wrong element order

如果在循环中重复调用poll,则可以验证相同的调用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67871280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档