天天看點

Java的優先隊列PriorityQueue詳解

一、優先隊列概述

  優先隊列PriorityQueue是Queue接口的實作,可以對其中元素進行排序,

可以放基本資料類型的包裝類(如:Integer,Long等)或自定義的類

對于基本資料類型的包裝器類,優先隊列中元素預設排列順序是升序排列

但對于自己定義的類來說,需要自己定義比較器

二、常用方法

peek()//傳回隊首元素
poll()//傳回隊首元素,隊首元素出隊列
add()//添加元素
size()//傳回隊列元素個數
isEmpty()//判斷隊列是否為空,為空傳回true,不空傳回false
           

三、優先隊列的使用

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.隊列儲存的是自定義類

//矩形類
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.優先隊列周遊

  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;
        }
    };