我在类里面使用的compareTo函数
public int compareTo(Book b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
当我添加一个优先级队列,其 id 顺序为 12 99 89 55 40 4 时,我得到的输出是:
4
40
12
99
55
89
我用来迭代 PriorityQueue 的代码是:
Iterator it = queue.iterator();
while(it.hasNext()){
Book b = (Book)it.next();
System.out.println(b.id);
}
这样的输出可能存在什么问题? 一旦我调用queue.remove()然后迭代,顺序似乎是正确的。
最佳答案
PriorityQueue
的迭代器不能保证按照元素类 (Book
) 的 Comparable
实现定义的顺序返回元素)。
来自 PriorityQueue
的 Javadoc:
This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
关于java - Java优先级队列中的compareTo工作不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44150690/