Java:优先级队列 [英] Java : Priority Queue

查看:323
本文介绍了Java:优先级队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的java程序

I have a java program which goes like this

public class PriorityQueueExample {

public class PriorityQueueExample {

public static void main(String[] args) {
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    pq.add(10);
    pq.add(1);
    pq.add(9);
    pq.add(2);
    pq.add(8);
    pq.add(3);
    pq.add(7);
    pq.add(4);
    pq.add(6);
    pq.add(5);
System.out.println(pq);

}

}

我的问题是为什么优先级队列不对它们排序。根据java规范,它实现了可比较和维护排序顺序(自然排序)

My Question is why does not the priority queue sort them. As per the java specs it implements comparable and maintains the sorting order(natural sorting)

我的程序输出如下:[1,2,3,4, 5,9,7,10,6,8]

My output of the program is as follows : [1, 2, 3, 4, 5, 9, 7, 10, 6, 8]

推荐答案

插入优先级队列不足以元素,因为它不按照排序顺序存储它们;它将它们存储在部分排序的堆顺序中。您必须移除循环中的元素才能对它们进行排序:

Insertion into a priority queue is not enough to sort a list of elements, since it doesn't store them in sorted order; it stores them in the partially sorted heap order. You have to remove the elements in a loop to sort them:

while (pq.size() > 0)
    System.out.println(pq.remove());

这篇关于Java:优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆