为什么 PriorityQueue 不能正常工作?

Why does PriorityQueue not work properly?

这是我的代码:

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}});

}

按我的想法,输入是new int[][]{{0, 2, 3}, {2, 5, 3}},输出应该是[0, -3][2, -3][2, 3][5, 3],但实际上显示的是[0, -3][2, 3][2, -3][5, 3]。谁能告诉我我的代码有什么问题?提前致谢。

原因是PriorityQueue<T>在迭代时没有对元素进行排序:

public Iterator<E> iterator() 的文档指出方法

Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.

要获得您期望的顺序,您需要从优先级队列中一个一个地删除元素,并打印它们:

while (heights.size() != 0) {
    int[] height = heights.poll();
    System.out.println(Arrays.toString(height));
}

此更改产生以下输出:

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

Demo.