我試圖創建一個priorityqueue,它的元素(整數對)與自然順序相反。我在網站上發現了一些嚴重的提示,但是在任何情況下,它都會給出相同的錯誤順序。PriorityQueue包含「對」,以相反的數字順序Java
PriorityQueue<Pair> pq = new PriorityQueue(4,
new Comparator<Pair>() {
public int compare(Pair a1, Pair a2) {
return a2.value.compareTo(a1.value);
}
});
pq.add(new Pair(1,15));
pq.add(new Pair(2,58));
pq.add(new Pair(3,55));
pq.add(new Pair(7,23));
Iterator<Pair> it = pq.iterator();
while(it.hasNext()) {
System.out.println(it.next().value);
}
這裏是Pair類
public class Pair implements Comparable {
public Integer name;
public Integer value;
public Pair(int name, int value) {
this.name = name;
this.value = value;
}
public int getname(){
return name;
}
public int getvalue() {
return value;
}
public int compare(Pair o1, Pair o2) {
Pair a1 = (Pair)o1;
Pair a2 = (Pair)o2;
if(a1.value>a2.value) {
return 1;
}
else if(a1.value<a2.value) {
return -1;
}
return 0;
}
@Override
public int hashCode() {
int hash = 3;
return hash;
}
@Override
public boolean equals(Object o) {
Pair a2 = (Pair)o;
return this.name == a2.name && this.value == a2.value;
}
public int compareTo(Object o) {
Pair a2 = (Pair)o;
if(this.value>a2.value) {
return 1;
}
else if(this.value<a2.value) {
return -1;
}
return 0;
}
}
如果我使用了「新的優先級Queue()「的構造函數,它給出了適當的自然排序。 感謝您的時間, 馬克
哇,謝謝你的快速回答!我從來沒有猜到,迭代器不會工作......尤其是因爲它與自然順序一起工作。 – 2011-03-27 20:40:41
@ jon-spectet:它確實給出了正確的順序,但是將我的隊列留空。編寫自己的迭代器是唯一的途徑? – 2011-03-29 10:02:06
@ alex-murphy:可能;老實說,我不確定。 – 2011-03-29 10:24:11