- 如果要使用优先队列(PriorityQueue),并且存储的元素已经实现了Comparable接口(定义了自然顺序),那么不需要单独提供比较器,优先队列会使用元素的自然顺序来进行排序。
import java.util.PriorityQueue;
class Person implements Comparable<Person> {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
return this.age - other.age;
}
}
public class Main {
public static void main(String[] args) {
PriorityQueue<Person> pq = new PriorityQueue<>();
pq.offer(new Person("Alice", 25));
pq.offer(new Person("Bob", 20));
}
}
- 如果元素没有实现Comparable接口,或者希望使用不同于元素的自然顺序的排序方式,那么可以提供一个自定义的比较器(Comparator)来定义元素的排序规则。
import java.util.PriorityQueue;
import java.util.Comparator;
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Comparator<Person> cmp=new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.age, p2.age);
}
};
PriorityQueue<Person> pq = new PriorityQueue<>(cmp);
pq.offer(new Person("Alice", 25));
pq.offer(new Person("Bob", 20));
}
}