如何在 Java 中使用自定义对象打印 PriorityQueue

How to Print PriorityQueue with Custom Object in Java

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

数据class:

class Mhswa {

    String nama;
    int thnMasuk;

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

    public String getNama() {
        return nama;
    }
}

比较器class:

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;
    }
}

主要class:

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++;
        }

    }
}

感谢您的帮助。

您可以使用迭代器,因为 PriorityQueue 实现了 Iterable:

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