【问题标题】:How to Print PriorityQueue with Custom Object in Java如何在 Java 中使用自定义对象打印 PriorityQueue
【发布时间】:2021-02-11 02:12:05
【问题描述】:

我想打印自定义对象的 PriorityQueue。但是当我看到任何官方文档和教程时,我必须使用 poll 方法。有什么方法可以在不删除元素的情况下打印?这是我的代码:

数据类:

class Mhswa {

    String nama;
    int thnMasuk;

    public Mhswa(String nama, int thnMasuk) {
        this.nama = nama;
        this.thnMasuk = thnMasuk;
    }

    public String getNama() {
        return nama;
    }
}

比较器类:

class MhswaCompare implements Comparator<Mhswa> {
    public int compare(Mhswa s1, Mhswa s2) {
        if (s1.thnMasuk < s2.thnMasuk)
            return -1;
        else if (s1.thnMasuk > s2.thnMasuk)
            return 1;
        return 0;
    }
}

主类:

public static void main(String[] args) {
        PriorityQueue<Mhswa> pq = new PriorityQueue<>(5, new MhswaCompare());
        pq.add(new Mhswa("Sandman", 2019));
        pq.add(new Mhswa("Ironman", 2020));
        pq.add(new Mhswa("Iceman", 2021));
        pq.add(new Mhswa("Landman", 2018));
        pq.add(new Mhswa("Wingman", 2010));
        pq.add(new Mhswa("Catman", 2019));
        pq.add(new Mhswa("Speedman", 2015));

        int i = 0;
        // the print section that have to use poll()
        while (!pq.isEmpty()) { 
            System.out.println("Data ke " + i + " : " + pq.peek().nama + " " + pq.peek().thnMasuk);
            pq.poll();
            i++;
        }

    }
}

感谢您的帮助。

【问题讨论】:

    标签: java queue comparator priority-queue


    【解决方案1】:

    您可以使用 Iterator,因为 PriorityQueue 实现了 Iterable:

    Iterator it = pq.iterator();
    while (it.hasNext()) { 
        Mhswa value = it.next();
        System.out.println("Data ke " + i + " : " + value.nama + " " + value.thnMasuk);
        i++;
    }
    

    【讨论】:

    • 是否有任何解决方法,所以我不必使用 poll() 方法,我想在打印部分下方添加 pq.remove(),但我当然不能这样做,因为所有项目都有已使用 poll() 删除
    • 也许我误解了这个例子。如果队列的唯一目的是打印其内容,则根本不需要轮询。
    • 我想按升序打印,例如“2010, 2015, 2018, ...”,如果我使用默认的 PriorityQueue 顺序,它将是“2010, 2018, 2015, ...” 我知道这就是 PriorityQueue 的工作原理,这使得性能良好。那么,是否有机会重写 compareTo 方法,使其无需轮询元素即可实现升序?
    • 您可以使用 Apache CollectionUtils 将 PQ 转换为列表并从最后打印出来。如果 PQ 的目的是对对象进行排序,那么直接对列表进行排序而不使用 PQ 可能会更好。
    • 好的,感谢您的解释,我只是想知道是否有任何方法可以覆盖默认优先级。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2021-11-02
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多