PriorityQueue(優先隊列)使用完整示例
package cc.cv;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* PriorityQueue(優先隊列)使用完整示例
* 采用PriorityQueue時裡面的每個元素按照一定標准的優先級進行存儲.
* 而這個優先級的標准我們可以用Comparator來自己定義.
*
* 參考資料:
* 1 http://blog.csdn.net/chengyingzhilian/article/details/8078032
* 2 http://java-er.com/blog/java-priority-queue/
* 3 http://blog.csdn.net/hantiannan/article/details/7623108
* Thank you very much
*
*/
public class PriorityQueueTest {
private int initialCapacity=10;
public static void main(String[] args) {
PriorityQueueTest priorityQueueTest=new PriorityQueueTest();
priorityQueueTest.test();
}
/**
* 將一群斑馬放入優先隊列PriorityQueue中.
* 既然是優先隊列PriorityQueue,那麼就有一個優先的標准.
* 在此就按照每個斑馬的身高優先將一群斑馬存在隊列中
*/
private void test(){
PriorityQueue priorityQueue=new PriorityQueue(initialCapacity, new ZebraComparator());
Zebra zebra1=new Zebra("a", 130);
priorityQueue.add(zebra1);
Zebra zebra2=new Zebra("b", 130);
priorityQueue.add(zebra2);
Zebra zebra3=new Zebra("c", 130);
priorityQueue.add(zebra3);
Zebra zebra4=new Zebra("d", 130);
priorityQueue.add(zebra4);
Zebra zebra5=new Zebra("a", 110);
priorityQueue.add(zebra5);
Zebra zebra6=new Zebra("c", 120);
priorityQueue.add(zebra6);
System.out.println("priorityQueue.size()="+priorityQueue.size());
//每個元素依次出隊,便於測試
while (!priorityQueue.isEmpty()){
System.out.println(priorityQueue.poll());
}
System.out.println("priorityQueue.size()="+priorityQueue.size());
}
//按照斑馬的身高進行排序,身高相同時再比較名字
class ZebraComparator implements Comparator {
@Override
public int compare(Object arg0, Object arg1) {
Zebra zebra0 = (Zebra) arg0;
Zebra zebra1 = (Zebra) arg1;
if (zebra0.getHeight() > zebra1.getHeight()) {
return 1;
}
// 身高相同時再比較名字
if (zebra0.getHeight() == zebra1.getHeight()) {
return zebra0.getName().compareTo(zebra1.getName());
}
if (zebra0.getHeight() < zebra1.getHeight()) {
return -1;
}
return 0;
}
}
/**
* 動物園裡的大熊貓和斑馬還是很可愛的。
* 看大熊貓的話,成都熊貓基地很爽.
* 看斑馬的話,北京動物園不錯,裡面還有需要仰著脖子看的長頸鹿......
* 在這裡就用斑馬舉例吧,它有名字和身高這兩個屬性
*/
private class Zebra{
private String name;
private int height;
public Zebra(String name, int height) {
super();
this.name = name;
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {
return "Zebra [name=" + name + ", height=" + height + "]";
}
}
}