簡體   English   中英

如何在Java中實現元組的優先級隊列,該隊列使用具有不同類型的兩個字段進行排序?

[英]How do I implement in Java a priority queue of a Tuple that sorts using both fields with different types?

我創建了一個名為Thread的類,它具有兩個字段:int index和long start_time,如下所示:

class Thread {
    public Thread(int index, long start_time) {
        this.index = index;
        this.start_time = start_time;
    }

    public int index;
    public long start_time;
}

之后,我創建了一個線程優先隊列,如下所示:

PriorityQueue<Thread> worker = new PriorityQueue<>();

因此,我將使用從0到n-1的數字的n個線程來填充此隊列。 它們都以0作為start_time開頭,如下所示:

for (int i = 0; i < numWorkers;i++){
            worker.add(new Threads(i , 0));
}  

然后我會及時添加作業,因此可以說作業是{4,3}; 如果Pqueue具有2個元素(0,0)和(1,0),它將變成(0,4)和(1,3),因為poll()將選擇0作為優先級(根據索引升序),但是下次poll()將首先彈出(1,3),因為3小於4(因此它按start_time排序上升,但如果它們相等,則按索引排序上升)。

我只是學習數據結構並使用Comparable和Comparator,所以這是我第一次使用它,但是大多數示例都沒有提到元組,或者它們只是按一個字段排序。 我的實現想法是這樣的:

class threadComparator implements Comparator<Thread> {
    @Override
    public int compare(Thread a, Thread b) {
        if (a.start_time==b.start_time){
            return a.index - b.index;
        }
        return a.start_time - b.start_time;
    }
}

根據我的IDE,我不能使用return a.start_time-b.start_time (不兼容的類型int找到long

在CodeGeeks中使用了此頁面作為示例,但是該示例不使用長類型。

最后,我應該如何在我的優先級隊列中將此threadComparator應用於此排序順序? 我假設是:

PriorityQueue<Thread> worker = new PriorityQueue<>(new threadComparator);

是這樣嗎? 我應該在threadComparator類中還是在Thread類中實現Comparator。 請不要在意,我已經在Google上搜索並在SO中進行了搜索,但我找不到類似的示例。 希望我的解釋很清楚。

2個long值的減法類型為long ,這就是為什么您不能返回的原因

a.start_time - b.start_time

此外請注意,如果允許使用負值,

a.index - b.index

a.start_time - b.start_time

可能溢出並返回無效結果。

最好像這樣實現compare

public int compare(Thread a, Thread b) {
    int c = Long.compare(a.start_time, b.start_time);
    return c == 0
                  ? Integer.compare(a.index, b.index) // compare index, if start_time is the same
                  : c; // if start_times are different, use the result of comparing the 2 fields
}

在Java 8中,您還可以像這樣構造一個比較器:

Comparator<Thread> comparator = Comparator.comparingLong(thread -> thread.start_time)
                                          .thenComparingInt(thread -> thread.index);

您幾乎處於正確的道路上,但是對於比較器,您必須返回int值:

  • 如果左側較小,則為負數
  • 如果相等則為0
  • 如果右側較小,則為正數

所以只要更換

return a.start_time - b.start_time;

通過

if (a.start_time < b.start_time)
   return -1;
if (a.start_time > b.start_time)
   return 1;
return 0;

暫無
暫無

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

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