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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM