1、優先隊列概述數組
優先隊列PriorityQueue是Queue接口的實現,能夠對其中元素進行排序,this
能夠放基本數據類型的包裝類(如:Integer,Long等)或自定義的類spa
對於基本數據類型的包裝器類,優先隊列中元素默認排列順序是升序排列code
但對於本身定義的類來講,須要本身定義比較器blog
2、經常使用方法排序
peek()//返回隊首元素 poll()//返回隊首元素,隊首元素出隊列 add()//添加元素 size()//返回隊列元素個數 isEmpty()//判斷隊列是否爲空,爲空返回true,不空返回false
3、優先隊列的使用接口
1.隊列保存的是基本數據類型的包裝類隊列
//自定義比較器,降序排列 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 */ }
2.隊列保存的是自定義類it
//矩形類 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 */ } }
3.優先隊列遍歷io
PriorityQueue的iterator()不保證以任何特定順序遍歷隊列元素。
若想按特定順序遍歷,先將隊列轉成數組,而後排序遍歷
示例
Queue<Integer> q = new PriorityQueue<>(cmp); int[] nums= {2,5,3,4,1,6}; for(int i:nums) { q.add(i); } Object[] nn=q.toArray(); Arrays.sort(nn); for(int i=nn.length-1;i>=0;i--) System.out.print((int)nn[i]+" "); /** * 輸出結果 * 6 5 4 3 2 1 */
4.比較器生降序說明
Comparator<Object> cmp = new Comparator<Object>() { public int compare(Object o1, Object o2) { //升序 return o1-o2; //降序 return o2-o1; } };