【发布时间】:2014-01-04 16:35:49
【问题描述】:
我想写一个程序,可以按优先队列排序项目
但是下面的代码不起作用,我不知道问题所在
有什么帮助吗? 提前感谢您的关注
public class SortingASequenceByPriorityQueue {
public static void main(String[] args) {
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(1000, new Comparator<Integer>() {
public int compare(Integer w1, Integer w2) {
if(w1.intValue()> w2.intValue())
return 1;
else if( w1.intValue()< w2.intValue())
return -1;
return 0;
}
});
pQueue.add(12);
pQueue.add(1);
pQueue.add(5);
pQueue.add(22);
pQueue.add(3);
pQueue.add(2);
pQueue.add(124);
pQueue.add(14);
pQueue.add(111);
pQueue.add(9);
pQueue.add(30);
Object[] ar = pQueue.toArray();
for (int i = 0; i< ar.length; i++){
System.out.println(ar[i].toString());
}
}
}
输出是这样的:
1 3 2 14 9 5 124 22 111 12 30
【问题讨论】:
-
这是在文档中指定的。 "返回一个包含此队列中所有元素的数组。这些元素没有特定顺序。"
-
看来您的目标是按升序对整数集合进行排序。当有其他/更好的选择时,为什么需要使用
PriorityQueue? -
阅读 Javadoc 可以回答您的问题。
标签: java sorting priority-queue