簡體   English   中英

優先隊列未保持排序順序

[英]Priority queue is not maintaining sorting order

優先隊列未保持排序順序我執行Comparable是否不正確? 輸出的排序順序不正確?

import java.util.PriorityQueue;

    class A implements Comparable 
    {
        int i;
        A(int i)
        {
            this.i =  i;

        }
        public int compareTo(Object obj)
        {
            return i - ((A)obj).i;
        }
        public String toString()
        {
            return Integer.toString(i);
        }

    }
    class Manager11
    {
        public static void main(String[] args) 
        {
            PriorityQueue pq =  new PriorityQueue();
            pq.add(new A(9));
            pq.add(new A(5));
            pq.add(new A(8));
            pq.add(new A(19));
            pq.add(new A(1));

            System.out.println(pq);
        }
}

輸出:[1、5、8、19、9]

在優先級隊列中,唯一的保證是磁頭是最低的(或最大的,取決於您的比較)。 內部結構不一定是排序列表。 實際上,在Java中,這是一個堆:

PriorityQueue

基於優先級堆的無界優先級隊列。

但是,如果您執行了一個循環,對第一個項目進行poll() ,然后一次又一次地打印它,直到優先級隊列為空。 元素應從最低到最大打印。

優先隊列不保證ordering 它使用的內部數據結構是Heap 但是無論何時輪詢,它都會按其優先級順序返回元素。 例如下面的代碼:

for (int i = 0; i < 5; i++) {
    System.out.print(pq.poll() + " ,");
}

給您輸出:

1 ,5 ,8 ,9 ,19 

您沒有正確實現Comparable :這是一個泛型類,因此應指定類型參數。 我想象你想要Comparable<A>

class A implements Comparable<A> {
  // ...

  @Override public int compare(A other) {
    return i - other.i;  // Cast is no longer required.
  }

  // ...
}

這不會更改代碼的輸出,只會擺脫強制類型轉換和警告。

此外,請勿使用減法比較整數,因為這無法處理溢出:請使用Integer.compare

return Integer.compare(i, other.i);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM