在Java中实现自定义的PriorityQueue,你需要遵循以下步骤:
Person
的类,其中包含name
和age
属性。public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
import java.util.Comparator;
public class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
}
import java.util.PriorityQueue;
public class CustomPriorityQueue {
public static void main(String[] args) {
PriorityQueue<Person> priorityQueue = new PriorityQueue<>(new AgeComparator());
priorityQueue.add(new Person("Alice", 30));
priorityQueue.add(new Person("Bob", 25));
priorityQueue.add(new Person("Charlie", 35));
while (!priorityQueue.isEmpty()) {
System.out.println(priorityQueue.poll());
}
}
}
运行上述代码,你将看到按年龄排序的Person对象输出。这就是如何在Java中实现自定义的PriorityQueue。