[java队列]——PriorityQueue

PriorityQueue介绍

上一篇[java队列]——ArrayBlockingQueue介绍了数组方式实现的阻塞队列。这篇将介绍PriorityQueue优先级队列。其简介如下:

  • 优先级队列,是0个或多个元素的集合,集合中的每个元素都有一个权重值,每次出队都弹出优先级最大或最小的元素。
  • 数据实现
  • 非线程安全
  • 自动扩容
  • 使用小顶堆作为实现

PriorityQueue内部实现

基本属性

public class PriorityQueue<E> extends AbstractQueue<E>
    implements java.io.Serializable {

	//默认容量
    private static final int DEFAULT_INITIAL_CAPACITY = 11;

    //存储元素的数组
    transient Object[] queue; // non-private to simplify nested class access

    //队列元素的数量
    private int size = 0;

    //比较器(通过比较器判断元素的权重大小)
    private final Comparator<? super E> comparator;

    //队列修改次数,所以PriorityQueue也是fast-fail的
    transient int modCount = 0; // non-private to simplify nested class access

构造方法

在这里插入图片描述
构造方法较多,主要可传入初始化的参数有:

  • 队列初始容量
  • 比较器,用于比较元素之间的大小

入队

	//add方法实际就是调用offer
	public boolean add(E e) {
        return offer(e);
    }

    public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
        	//如果容量不够则扩容
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
        	//入队,自下而上堆化,i是待插入的位置(并非待插入元素正在的位置,会进行堆化调整位置)
            siftUp(i, e);
        return true;
    }


	private void siftUp(int k, E x) {
		//根据是否有比较器,选择堆化时比较元素大小的方式
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }

    @SuppressWarnings("unchecked")
    private void siftUpComparable(int k, E x) {
    	//使用默认比较器
        Comparable<? super E> key = (Comparable<? super E>) x;
        while (k > 0) {
        	//找到待插入位置的父节点
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            //待插入元素与父节点比较,如果比父节点大,所以找到了真正要插入的位置,break提出循环。
            if (key.compareTo((E) e) >= 0)
                break;
            //比父节点小,则与父节点交换位置,继续循环
            queue[k] = e;
            k = parent;
        }
        //找到位置,插入元素
        queue[k] = key;
    }

    @SuppressWarnings("unchecked")
    private void siftUpUsingComparator(int k, E x) {
    	//使用传入的构造器,堆化过程与siftUpComparable一致
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (comparator.compare(x, (E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = x;
    }

结论:

  • 入队的方法有add和offer,add实际上也是调用offer方法
  • 队列满时,会自动扩容
  • 插入元素时,自下而上堆化,其实就是标准的堆插入元素
  • PriorityQueue是一个小顶堆实现的

扩容

	private void grow(int minCapacity) {
        int oldCapacity = queue.length;
        // 如果旧容量小于64,则翻倍扩容,否则扩容增加旧容量的一半
        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
                                         (oldCapacity + 2) :
                                         (oldCapacity >> 1));
        // 扩容后,最大容量不能超过MAX_ARRAY_SIZE = 
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // copy方式扩容
        queue = Arrays.copyOf(queue, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

出队

	public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

	public E poll() {
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        //出队,出的是队头
        E result = (E) queue[0];
        //接着获取队尾元素
        E x = (E) queue[s];
        //将队尾元素删除
        queue[s] = null;
        if (s != 0)
        	//将队尾元素移到队头,自上而下堆化
            siftDown(0, x);
        return result;
    }
    private void siftDown(int k, E x) {
        if (comparator != null)
            siftDownUsingComparator(k, x);
        else
            siftDownComparable(k, x);
    }

    @SuppressWarnings("unchecked")
    private void siftDownComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>)x;
        //因为叶子节点占了一半元素,所以只需要比较一半就到位置了。
        int half = size >>> 1;        // loop while a non-leaf
        while (k < half) {
        	//取左子节点
            int child = (k << 1) + 1; // assume left child is least
            Object c = queue[child];
            //取右子节点
            int right = child + 1;
            if (right < size &&
                ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
                //取左右节点中最小的节点
                c = queue[child = right];
            if (key.compareTo((E) c) <= 0)
            	//如果原队尾元素比左右子节点都小,那就找到位置了,退出循环
                break;
            //如果原队尾元素比左右最小的节点大,则交换位置,继续循环
            queue[k] = c;
            k = child;
        }
        //将队尾元素插入
        queue[k] = key;
    }

    @SuppressWarnings("unchecked")
    private void siftDownUsingComparator(int k, E x) {
    	//使用自定义的比较器,逻辑与siftDownComparable一致
        int half = size >>> 1;
        while (k < half) {
            int child = (k << 1) + 1;
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                comparator.compare((E) c, (E) queue[right]) > 0)
                c = queue[child = right];
            if (comparator.compare(x, (E) c) <= 0)
                break;
            queue[k] = c;
            k = child;
        }
        queue[k] = x;
    }

结论:

  • 将队头元素返回->将队尾元素移到队头->一直与其左右子节点中的最小节点做比较并交换位置->直到原队尾元素比起左右子节点都小,则是原队尾元素应该保存的位置。
  • 这就是标准的堆的删除堆顶元素

取队头元素,并不出队

	public E element() {
        E x = peek();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

	public E peek() {
        return (size == 0) ? null : (E) queue[0];
    }

PriorityQueue总结

  • 数据实现,自动扩容,无界
  • 非线程安全
  • 使用小顶堆作为实现,入队就是堆的插入,出队就是堆的删除堆顶元素

Queue接口

上一篇介绍[java队列]——ArrayBlockingQueue的时候,顺带介绍了BlockingQueue接口,它是一个阻塞队列的接口,其实这个接口继承了Queue接口。Queue是所有队列的最顶级接口,提供了队列最基本的操作方法。

队列操作正常返回特定值可能抛出异常
入队addoffer
出队removepoll
检查elementpeek
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值