最近在使用 Java 的 PriorityQueue 类的时候发现,PriorityQueue类能保证先输出优先级高的元素,但是对于优先级相同的元素时,它并不能保证先进先出。
示例如下:
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* 66
* 44 55
* 44 22 44 33
* 22 22 (44)
*/
class MyInteger {
// 插入顺序
int order;
int value;
public MyInteger(int order, int value) {
this.order = order;
this.value = value;
}
public void setOrder(int order) {
this.order = order;
}
public void setValue(int value) {
this.value = value;
}
@Override
public String toString() {
return "MyInteger{" +
"order=" + order +
", value=" + value +
'}';
}
}
public class Main {
public static void main(String[] args) {
// 创建一个优先级队列
PriorityQueue<MyInteger> priorityQueue = new PriorityQueue<>(new Comparator<MyInteger>() {
@Override
public int compare(MyInteger o1, MyInteger o2) {
return o2.value - o1.value