1,根据年龄小的先出优先级
class Person implements Comparable<Person>{
public int age;
Person(int age){
this.age=age;
}
public int compareTo(Person other){
return age-other.age;
}
}
public class Main {
public static void main (String[] args) {
PriorityQueue<Person> q=new PriorityQueue<Person>();
Person a=new Person(10);
Person b=new Person(20);
q.offer(a);
q.offer(b);
System.out.println(q.peek().age);
}
}
2,根据年龄大的先出优先级
class Person implements Comparable<Person>{
public int age;
Person(int age){
this.age=age;
}
public int compareTo(Person other){
return other.age-age;
}
}
public class Main {
public static void main (String[] args) {
PriorityQueue<Person> q=new PriorityQueue<Person>();
Person a=new Person(10);
Person b=new Person(20);
q.offer(a);
q.offer(b);
System.out.println(q.peek().age);
}
}
Java的优先队列是小根堆(堆顶的元素为最小元素),是根据自然排序来进行优先级的判断,所以自定义的类想要加进优先队列中必须先实现Comparable接口,编写compareTo的方法,方可以使用!