Java中的PriorityQueue如何排序重复条目?

Pet*_*etr 8 java priority-queue

这可能听起来很愚蠢,但是当你有(键,值)对的对象并且你根据键对它们进行排序时它是有意义的.用代码说明我的观点:

public class Pair implements Comparable<Pair> {
    private int value;
    private int key;

    public Pair(int key, int value) {
        this.key   = key;
        this.value = value;
    }

    @Override
    public int compareTo(Pair o) {
        if (this.key > o.key)
            return 1;
        else if (this.key < o.key)
            return -1;
        return 0;
    }
}

public class program {
    public static void main(String[] args) {
        PriorityQueue<Pair> queue = new PriorityQueue<Pair>;
        queue.add(new Pair(1,1));
        queue.add(new Pair(1,2));
        queue.add(new Pair(1,3));

        Pair pair = queue.poll(); // What would be in pair?
    }
}
Run Code Online (Sandbox Code Playgroud)

会有什么pair?第一个或最后一个添加的元素?或者他们中的任何一个都无法决定?

Evg*_*eev 8

PriorityQueue API对此情况不做任何承诺:

此队列的头部是指定排序的最小元素.如果多个元素被绑定为最小值,则头部是这些元素之一 - 关系被任意打破.队列检索操作轮询,删除,查看和元素访问队列头部的元素.

但它很容易测试.添加toString配对

@Override
public String toString() {
    return key + " " + value;
}
Run Code Online (Sandbox Code Playgroud)

并打印投票结果

    Pair pair = queue.poll(); // What would be in pair?
    System.out.println(pair);
Run Code Online (Sandbox Code Playgroud)

它打印

1 1
Run Code Online (Sandbox Code Playgroud)