java中的priorityqueue一般也就是代表優先隊列。
這是屬於Queue接口的實現,能夠對其中元素進行排序,還能放基本數據類型的包裝類或是自定義的類,而對於基本數據類型的包裝類,優先隊列中元素一般是默認排列順序為升序排列的。
參考範例:
隊列保存的是基本數據類型的包裝類,具體代碼為:
//自定義比較器,降序排列
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer e1, Integer e2) {
return e2 - e1;
}
};
public static void main(String[] args) {
//不用比較器,默認升序排列
Queue<Integer> q = new PriorityQueue<>();
q.add(3);
q.add(2);
q.add(4);
while(!q.isEmpty())
{
System.out.print(q.poll()+" ");
}
/**
* 輸出結果
* 2 3 4
*/
//使用自定義比較器,降序排列
Queue<Integer> qq = new PriorityQueue<>(cmp);
qq.add(3);
qq.add(2);
qq.add(4);
while(!qq.isEmpty())
{
System.out.print(qq.poll()+" ");
}
/**
* 輸出結果
* 4 3 2
*/
}
隊列保存的是自定義類,具體代碼為:
//矩形類
class Node{
public Node(int chang,int kuan)
{
this.chang=chang;
this.kuan=kuan;
}
int chang;
int kuan;
}
public class Test {
//自定義比較類,先比較長,長升序排列,若長相等再比較寬,寬降序
static Comparator<Node> cNode=new Comparator<Node>() {
public int compare(Node o1, Node o2) {
if(o1.chang!=o2.chang)
return o1.chang-o2.chang;
else
return o2.kuan-o1.kuan;
}
};
public static void main(String[] args) {
Queue<Node> q=new PriorityQueue<>(cNode);
Node n1=new Node(1, 2);
Node n2=new Node(2, 5);
Node n3=new Node(2, 3);
Node n4=new Node(1, 2);
q.add(n1);
q.add(n2);
q.add(n3);
Node n;
while(!q.isEmpty())
{
n=q.poll();
System.out.println("長: "+n.chang+" 寬:" +n.kuan);
}
/**
* 輸出結果
* 長: 1 寬:2
* 長: 2 寬:5
* 長: 2 寬:3
*/
}
}