Java 为什么PriorityQueue不能正常工作?

Java 为什么PriorityQueue不能正常工作?,java,priority-queue,Java,Priority Queue,这是我的密码: public static List<int[]> getSkyline(int[][] buildings) { List<int[]> res = new ArrayList<>(); PriorityQueue<int[]> heights = new PriorityQueue<>(buildings.length * 2, new Comparator<int[]>() {

这是我的密码:

public static List<int[]> getSkyline(int[][] buildings) {
    List<int[]> res = new ArrayList<>();

    PriorityQueue<int[]> heights = new PriorityQueue<>(buildings.length * 2, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            if (o1[0] == o2[0]) {
                return o1[1] - o2[1];
            } else {
                return o1[0] - o2[0];
            }
        }
    });

    for (int[] h : buildings) {
        heights.add(new int[]{h[0], -h[2]});
        heights.add(new int[]{h[1], h[2]});
    }


    for (int[] height : heights) {
        System.out.println(Arrays.toString(height));
    }

    return res;
}

public static void main(String[] args) {
    getSkyline(new int[][]{{0, 2, 3}, {2, 5, 3}});

}
公共静态列表getSkyline(int[][]建筑物){
List res=new ArrayList();
优先级队列高度=新的优先级队列(buildings.length*2,新的比较器(){
@凌驾
公共整数比较(整数[]o1,整数[]o2){
if(o1[0]==o2[0]){
返回o1[1]-o2[1];
}否则{
返回o1[0]-o2[0];
}
}
});
对于(int[]h:建筑物){
添加(新的int[]{h[0],-h[2]});
添加(新的int[]{h[1],h[2]});
}
对于(int[]高度:高度){
System.out.println(Arrays.toString(height));
}
返回res;
}
公共静态void main(字符串[]args){
getSkyline(新的int[][{{0,2,3},{2,5,3});
}

在我看来,由于输入是
newint[]{{0,2,3},{2,5,3}
,所以输出应该是
[0,-3][2,-3][2,3][5,3]
,但实际上它显示的是
[0,-3][2,3][2,-3][5,3]
。有人能告诉我我的密码出了什么问题吗?提前感谢。

原因是
PriorityQueue
不会在迭代时对元素排序:

public Iterator Iterator()
的文档说明该方法

返回此队列中元素的迭代器。迭代器不会以任何特定顺序返回元素

要获得预期的顺序,您需要从优先级队列中逐个删除元素,然后打印它们:

while (heights.size() != 0) {
    int[] height = heights.poll();
    System.out.println(Arrays.toString(height));
}
此更改将产生以下输出:

[0, -3]
[2, -3]
[2, 3]
[5, 3]