在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。