2010年9月16日 星期四

Java筆記-PriorityQueue 優先權佇列

PriorityQueue會自動依照自然法則來排序,範例: import java.util.*;
public class Ex1 {
  public static void main(String[] args) {
    PriorityQueue<String> pq = new PriorityQueue<String> ();
    pq.offer("c");
    pq.offer("a");
    pq.offer("b");
    String s;
    while((s = pq.poll()) != null) {
       System.out.print(s + ", ");
    }
  }
}

 

##ReadMore##
自定義的PriorityQueue要實作Comparator介面,建構子是用 public PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
其中initialCapacity是初始大小,comparator是要求傳入Comparator物件,範例: public class Ex2 {
  public static void main(String[] args) {
    Comparator<String> c = new Comparator<String>(){
      public int compare(String a, String b){
        return a.compareTo(b) * -1;
      }
    };
    PriorityQueue<String> pq = new PriorityQueue<String> (3, c);
    pq.offer("c");
    pq.offer("a");
    pq.offer("b");
    String s;
    while((s = pq.poll()) != null) {
      System.out.print(s + ", ");
    }
  }
}

1 意見 :

John 提到...

剛好用到, 感謝分享 ^^

張貼留言