一、概述

优先队列PriorityQueueQueue接口的实现,可以对其中元素进行排序,默认排列顺序是升序排列

可以放基本数据类型的包装类(如:Integer,Long等)或自定义的类

底层:二叉堆

特点:堆的某个节点总是不大于其父亲节点的值

 

二、常用方法

peek()//返回队首元素
poll()//返回队首元素,队首元素出队列
add()//添加元素
size()//返回队列元素个数
isEmpty()//判断队列是否为空,为空返回true,不空返回false

 

三、使用

//自定义比较器,降序排列
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 
         */
}

 

说明:比较器生降序

Comparator<Object> cmp = new Comparator<Object>() {
        public int compare(Object o1, Object o2) {
            //升序
            return o1-o2;
            //降序
            return o2-o1;
        }
    };

 

 

 

博客借鉴https://www.cnblogs.com/wei-jing/p/10806236.html

posted on 2021-09-20 22:45  smile学子  阅读(73)  评论(0)    收藏  举报