优先级队列未维护排序顺序 我是否未正确实施 Comparable?错误的排序顺序作为输出出现?
import java.util.PriorityQueue;
class A implements Comparable
{
int i;
A(int i)
{
this.i = i;
}
public int compareTo(Object obj)
{
return i - ((A)obj).i;
}
public String toString()
{
return Integer.toString(i);
}
}
class Manager11
{
public static void main(String[] args)
{
PriorityQueue pq = new PriorityQueue();
pq.add(new A(9));
pq.add(new A(5));
pq.add(new A(8));
pq.add(new A(19));
pq.add(new A(1));
System.out.println(pq);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:[1, 5, 8, 19, 9]
在优先级队列中,唯一的保证是头部最低(或最大,取决于您的比较)。内部结构不一定是排序列表。实际上,在 Java 中,它是一个堆:
优先队列
基于优先级堆的无界优先级队列。
但是,如果您poll()对第一项进行循环,则将其打印,一次又一次,直到优先级队列为空。元素应该从最低到最大的元素打印。