標籤:
該文章轉自:http://blog.csdn.net/hiphopmattshi/article/details/7334487
優先順序隊列是不同於先進先出隊列的另一種隊列。每次從隊列中取出的是具有最高優先權的元素。
PriorityQueue是從JDK1.5開始提供的新的資料結構介面。
如果不提供Comparator的話,優先隊列中元素預設按自然順序排列,也就是數字預設是小的在隊列頭,字串則按字典序排列。
由於網上的資料大多將優先順序隊列各個方法屬性,很少有執行個體講解的,為方便大家以後使用,我就寫了個demo~
如果想實現按照自己的意願進行優先順序排列的隊列的話,需要實現Comparator介面。下面的方法,實現了根據某個變數,來進行優先順序隊列的建立。
1 import java.util.Comparator; 2 import java.util.PriorityQueue; 3 import java.util.Queue; 4 5 public class test { 6 private String name; 7 private int population; 8 public test(String name, int population) 9 {10 this.name = name;11 this.population = population;12 }13 public String getName()14 {15 return this.name;16 }17 18 public int getPopulation()19 {20 return this.population;21 }22 public String toString()23 {24 return getName() + " - " + getPopulation();25 }26 public static void main(String args[])27 {28 Comparator<test> OrderIsdn = new Comparator<test>(){29 public int compare(test o1, test o2) {30 // TODO Auto-generated method stub31 int numbera = o1.getPopulation();32 int numberb = o2.getPopulation();33 if(numberb > numbera)34 {35 return 1;36 }37 else if(numberb<numbera)38 {39 return -1;40 }41 else42 {43 return 0;44 }45 46 }47 48 49 50 };51 Queue<test> priorityQueue = new PriorityQueue<test>(11,OrderIsdn);52 53 54 55 test t1 = new test("t1",1);56 test t3 = new test("t3",3);57 test t2 = new test("t2",2);58 test t4 = new test("t4",0);59 priorityQueue.add(t1);60 priorityQueue.add(t3);61 priorityQueue.add(t2);62 priorityQueue.add(t4);63 System.out.println(priorityQueue.poll().toString());64 }65 }
輸出結果:
t3 - 3
結論:
PriorityQueue根據Comparator中實現的比較方法優先加入比較值最大的對象
《轉》JAVA中PriorityQueue優先順序隊列使用方法