PriorityQueue是在Java SE 5.0中,引入了的Collection API,他與傳統queue不同的是,PriorityQueue並非是FIFO的隊列,PriorityQueue會對裏面的元素按照優先級進行排序。他是如何按優先級排序的呢?
PriorityQueue隊列按照在構造時所指定的順序對元素排序,既可以根據元素的自然順序來指定排序(參閱 Comparable),也可以根據 Comparator來指定,這取決於使用哪種構造方法。優先級隊列不允許 null 元素。依靠自然排序的優先級隊列還不允許插入不可比較的對象(這樣做可能導致 ClassCastException)。
PriorityQueue隊列的頭是按指定排序方式的最小元素。如果多個元素都是最小值,則頭是其中一個元素——選擇方法是任意的。
下面看一個使用Comparator的例子:
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class test {
private String name;
private int population;
public test(String name, int population)
{
this.name = name;
this.population = population;
}
public String getName()
{
return this.name;
}
public int getPopulation()
{
return this.population;
}
public String toString()
{
return getName() + " - " + getPopulation();
}
public static void main(String args[])
{
Comparator<test> OrderIsdn = new Comparator<test>(){
public int compare(test o1, test o2) {
// TODO Auto-generated method stub
int numbera = o1.getPopulation();
int numberb = o2.getPopulation();
if(numberb > numbera)
{
return 1;
}
else if(numberb<numbera)
{
return -1;
}
else
{
return 0;
}
}
};
Queue<test> priorityQueue = new PriorityQueue<test>(11,OrderIsdn);
test t1 = new test("t1",1);
test t3 = new test("t3",3);
test t2 = new test("t2",2);
test t4 = new test("t4",0);
priorityQueue.add(t1);
priorityQueue.add(t3);
priorityQueue.add(t2);
priorityQueue.add(t4);
System.out.println(priorityQueue.poll().toString());
}
}
輸出是:
t4 t1 t2 t3
再看一個試用comparable的例子:
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class test implements Comparable{
private String name;
private int population;
public test(String name, int population)
{
this.name = name;
this.population = population;
}
public String getName()
{
return this.name;
}
public int getPopulation()
{
return this.population;
}
public String toString()
{
return getName() + " - " + getPopulation();
}
public int compareTo(test o1) {
int numbera = o1.getPopulation();
int numberb = this.getPopulation();
if(numberb > numbera)
{
return 1;
}
else if(numberb<numbera)
{
return -1;
}
else
{
return 0;
}
}
public static void main(String args[])
{
Queue<test> priorityQueue = new PriorityQueue<test>();
test t1 = new test("t1",1);
test t3 = new test("t3",3);
test t2 = new test("t2",2);
test t4 = new test("t4",0);
priorityQueue.add(t1);
priorityQueue.add(t3);
priorityQueue.add(t2);
priorityQueue.add(t4);
System.out.println(priorityQueue.poll().toString());
}
}
輸出是一樣的。