Java優先佇列使用
阿新 • • 發佈:2019-01-29
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的方法,方可以使用!