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 意見 :
剛好用到, 感謝分享 ^^
張貼留言