[英]How to Print PriorityQueue with Custom Object in Java
I want to print PriorityQueue of custom object.我想打印自定义对象的 PriorityQueue。 But when i see any official docs and tutorial, i have to use poll method.但是当我看到任何官方文档和教程时,我必须使用 poll 方法。 Is there any way i can print without removing the element?有什么方法可以在不删除元素的情况下进行打印? Here is my code:这是我的代码:
Data class:数据类:
class Mhswa {
String nama;
int thnMasuk;
public Mhswa(String nama, int thnMasuk) {
this.nama = nama;
this.thnMasuk = thnMasuk;
}
public String getNama() {
return nama;
}
}
Comparator 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;
}
}
Main 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++;
}
}
}
Thanks for the help.谢谢您的帮助。
You could use an Iterator since PriorityQueue implements Iterable:您可以使用迭代器,因为 PriorityQueue 实现了 Iterable:
Iterator it = pq.iterator();
while (it.hasNext()) {
Mhswa value = it.next();
System.out.println("Data ke " + i + " : " + value.nama + " " + value.thnMasuk);
i++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.