PriorityQueue源码分析

常量

/** 默认初始化队列长度 */
	private static final int DEFAULT_INITIAL_CAPACITY = 11;
	
	/**
	 * 优先队列表示为一个平衡二叉堆:queue[n]节点的两个子节点
	 * 是queue[2*n+1]和queue[2*(n+1)]。优先队列通
	 * 过comparator保持顺序,或当comparator为null时通过
	 * 元素的自然顺序,对于每个在堆里的节点n和每个n的子节点d,n<=d。
	 * 当queue非空时,队列里最小的元素是queue[0]。
	 * 
     */
    transient Object[] queue; // 非私有的来简化内部类的访问 non-private to simplify nested class access

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

    /**
     *  比较器,如果优先队列使用元素的自然顺序则为null
     */
    private final Comparator<? super E> comparator;

    /**
     * 该优先队列从构造开始的次数。查看AbstractList详细的细节。
     */
    transient int modCount = 0; // non-private to simplify nested class access

插入操作 add()

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
            siftUp(i, e);
        return true;
    }
	/**
	 * 在k位置插入item x,通过x上移直到大于或等于父节点或者就是root来维持堆不变。     * 
     *
              * 使用与操作和比较器来简化加速。Comparable和Comparator版本
              * 被分为不同方法,这些方法在其他方面是相同的。
     *(与shiftDown类似.)
     *
     * @param k  填充的位置
     * @param x  插入的item
     */
    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];
            if (key.compareTo((E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = key;
    }
    
    @SuppressWarnings("unchecked")
    private void siftUpUsingComparator(int k, E x) {
        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;
    }

poll() 获取并删除

@SuppressWarnings("unchecked")
	    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;
	    }
	   /**
	    * 插入item x到k位置,通过多次将x降级到小于等于它的子节点
	    * 或者是叶子节点来维持不变。
	     *
	     * @param k 填充位置
	     * @param x 插入的节点
	     */
	    private void siftDown(int k, E x) {
	        if (comparator != null)
	            siftDownUsingComparator(k, x);
	        else
	            siftDownComparable(k, x);
	    }

	 @SuppressWarnings("unchecked")
	    private void siftDownUsingComparator(int k, E x) {
		 	//half为父节点位置
	        int half = size >>> 1;
	        //说明k有孩子节点
	        while (k < half) {
	        	//child为k的左孩子节点位置
	            int child = (k << 1) + 1;
	            Object c = queue[child];
	            //right为k的右孩子节点位置
	            int right = child + 1;
	            //有右孩子,左右两个子节点谁小跟谁换
	            if (right < size &&
	                comparator.compare((E) c, (E) queue[right]) > 0)
	            	//c为小的那个
	                c = queue[child = right];
	            if (comparator.compare(x, (E) c) <= 0)
	                break;
	            queue[k] = c;
	            k = child;
	        }
	        queue[k] = x;
	    }

在这里插入图片描述

实例

import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
public class MyPriorityQueue {
	public static void main(String[] args) {
		//优先队列自然顺序
		PriorityQueue<Integer> q = new PriorityQueue<>(7);
		q.add(5);
		q.add(33);
		q.add(4);
		Iterator iterator = q.iterator();
		while(iterator.hasNext()) {
			System.out.println(q.poll());
		}
	
		//通过comparator来改变优先队列顺序
		PriorityQueue<Demo> pq = new PriorityQueue<Demo>(7,new Demo());
		pq.add(new Demo(5,"s1"));
		pq.add(new Demo(33,"s2"));
		pq.add(new Demo(51,"s3"));
		pq.add(new Demo(15,"s4"));
		
		Iterator iteratorq = pq.iterator();
		while(iteratorq.hasNext()) {
			System.out.println(pq.poll().getAge());
		}
	}
	
	
	static class Demo implements Comparator<Demo>{

		private int age;
		private String name;
		
		public Demo() {
		}
		public Demo(int age, String name) {
			super();
			this.age = age;
			this.name = name;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}

		@Override
		public int compare(Demo o1, Demo o2) {
			return o2.age - o1.age;
		}

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值