这可能听起来很愚蠢,但是当你有(键,值)对的对象并且你根据键对它们进行排序时它是有意义的.用代码说明我的观点:
public class Pair implements Comparable {
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 queue = new PriorityQueue;
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?
}
}
什么会成对?第一个或最后一个添加的元素?或者他们中的任何一个都无法决定?