PriorityQueue是在Java SE 5.0中,引入了的Collection API,他与传统queue不同的是,PriorityQueue并非是FIFO的队列,PriorityQueue会对里面的元素按照优先级进行排序。他是如何按优先级排序的呢?
PriorityQueue队列按照在构造时所指定的顺序对元素排序,既可以根据元素的自然顺序来指定排序(参阅 Comparable),也可以根据 Comparator来指定
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());
}
}
输出是一样的。