簡體   English   中英

Java PriorityQueue 比較器

[英]Java PriorityQueue comparator

假設我有一個shoeCollection鞋碼和鞋品牌的shoeCollection類。 如何修改比較器,使其根據鞋碼對priorityQueue排序?

我知道優先級隊列已經有一個內置的比較器,但由於我的對象不是整數或雙精度數,我想我需要自己編寫。

這是我現在的比較器

static class ShoeComparator implements Comparator<shoes>
{
    @Override
    public int compare(shoes x, shoes y)
    {
        if(x.getID() > y.getID()){
            return 1;
        }
        if(x.getID() < y.getID()){
            return -1;
        }
        return 0;
    }
}

然后我聲明一個新的 Shoe 優先隊列,如下所示

private static Comparator<shoes> comparator = new shoeComparator();
private static PriorityQueue<shoes> list = new PriorityQueue<shoes>(10001, comparator);

我試着加了一些鞋子,看看結果如何

    list.add(new shoes(56.0, "Nike"));
    list.add(new shoes(47.0, "Addidas"));
    list.add(new shoes(93.0, "Puma"));
    list.add(new shoes(3.0, "Vans"));

在 Main 中測試

for(int i = 0; i < list.size(); i++){
        System.out.println(list.poll().getID());

    }

//3.0 47.0

僅注冊了 3.0 和 47.0 的 ID。 我的比較器有問題嗎?

似乎它只會返回前 2 個 ID 而忽略其余的 ID,但是當我調用list.size()它返回 4,這是正確的。 我找不到問題所在。

您可以創建PriorityQueue並在構造函數中放置比較器代碼。

例子:

PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(10, new Comparator<Integer>()
{
    @Override
    public int compare(Integer o1, Integer o2)
    {
        // Logic here
        return 0;
    }
});

您可以在 PriorityQueue 實例化期間內聯創建自定義比較器。

假設您的 Shoe 類如下所示:

public class Shoe {
    private double size;
    private String brand;

    public Shoe(double size, String brand) {
        this.size = size;
        this.brand = brand;
    }

    public double getSize() {
        return size;
    }
}

您可以通過執行以下操作來創建一個按尺碼對鞋子進行排序的 PriorityQueue:

PriorityQueue<Shoe> shoePQ = new PriorityQueue<>(10000, new Comparator<Shoe>() {
    @Override
    public int compare(Shoe s1, Shoe s2) {
        return s1.getSize()-s2.getSize();
    });
}

這將使鞋子從小到大排序。 如果你想要相反的順序,你可以用return s2.getSize()-s1.getSize();替換compare()的主體return s2.getSize()-s1.getSize();

暫無
暫無

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

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