我有两个X&Y数组,我将从中创建对Xi & Yi。现在,我想将它们添加到priorityQueue中,以便检索队列中当前可用的最大对。从最大我指的是最大'X‘的对,如果存在多个相等的较大的'X',那么优先考虑'Y’。到目前为止,我已经尝试了三种方法,但它们都没有奏效。
// 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 );
}// 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 );
}// 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 );
}// 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)
我知道我想在这里实现什么,可以使用其他的数据结构,比如带有自定义比较器的对的列表,但是我想知道这里的错误是什么,或者我在这里遗漏了什么。谢谢。
发布于 2021-06-07 12:07:23
优先级队列的元素已经按正确的顺序排列。您被打印的顺序误导了--参见PriorityQueue.toString wrong element order
如果在循环中重复调用poll,则可以验证相同的调用。
https://stackoverflow.com/questions/67871280
复制相似问题