2011-03-27 73 views
0

我試圖創建一個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()「的構造函數,它給出了適當的自然排序。 感謝您的時間, 馬克

回答

3

從文檔爲PriorityQueue.iterator()

返回在此隊列中的元素的迭代器。迭代器不會以任何特定順序返回元素。

如果你想出來的優先順序,保持通話poll(),直到它返回null

Pair pair; 
while((pair = pq.poll()) != null) { 
    System.out.println(pair.value); 
} 

,打印58,55,23,15,你要尋找的。

+0

哇,謝謝你的快速回答!我從來沒有猜到,迭代器不會工作......尤其是因爲它與自然順序一起工作。 – 2011-03-27 20:40:41

+0

@ jon-spectet:它確實給出了正確的順序,但是將我的隊列留空。編寫自己的迭代器是唯一的途徑? – 2011-03-29 10:02:06

+0

@ alex-murphy:可能;老實說,我不確定。 – 2011-03-29 10:24:11

0

而不是「return a2.value.compareTo(a1.value);」 你應該直接使用((a2.value> a1.value)?1:((a2.value == a1.value)?0:-1));

+1

爲什麼?你的代碼顯然難以閱讀,國際海事組織。是的,它避免了潛在的拳擊 - 但我不會在此基礎上改變它。原始比較代碼正常工作。 – 2011-03-27 17:26:56