【发布时间】: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