Java 优先队列PriorityQueue

Java中的优先队列Priority的就是一个大根堆,常用的方法有:
在这里插入图片描述
peek和poll方法都会返回堆顶元素,不同点是poll方法会将堆顶元素弹出,而peek只是返回堆顶元素。

下面是Priority的属性:

transient Object[] queue;  //存储队列中的数据
int size; //队列中元素的个数
private final Comparator<? super E> comparator;//比较器

还有两个常量:

private static final int DEFAULT_INITIAL_CAPACITY = 11;//默认初始容量
/**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//数组的最大长度

然后是构造方法,构造方法主要是两个参数:容量和比较器,然后根据容量创建一个数组。

public PriorityQueue() {
        this(DEFAULT_INITIAL_CAPACITY, null);
    }
    
public PriorityQueue(int initialCapacity) {
        this(initialCapacity, null);
    }

public PriorityQueue(Comparator<? super E> comparator) {
        this(DEFAULT_INITIAL_CAPACITY, comparator);
    }
    
public PriorityQueue(int initialCapacity,
                         Comparator<? super E> comparator) {
        // Note: This restriction of at least one is not actually needed,
        // but continues for 1.5 compatibility
        if (initialCapacity < 1)
            throw new IllegalArgumentException();
        this.queue = new Object[initialCapacity];
        this.comparator = comparator;
    }

接下来看一下常用的添加删除方法,数据结构中堆排序的实现主要依靠两个操作:创建堆和调整堆。由于优先队列是一个一个插入的,所以不需要创建堆这个操作,在Priority中调整堆主要是两个方法siftUp和siftDown。

先来看siftUp

private void siftUp(int k, E x) {
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }

参数k:添加元素的位置,通常是size。
参数x:要添加的元素。
这里的两个方法siftUpUsingComparator和siftUpComparable功能相同区别是前者使用构造方法传入的构造器,后者使用默认的构造器。

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

代码很简单,就是向上调整堆,当前节点大于父节点就要交换两个节点,继续向上比较。这样在插入一个新节点的时候就能保证堆的结构不被破坏。
与之类似,siftDown:向下调整:

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

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);
    siftUp(i, e);
    size = i + 1;
    return true;
}

在最后添加元素所以向上调整

peek方法

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

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

contain方法

public boolean contains(Object o) {
    return indexOf(o) >= 0;
}
private int indexOf(Object o) {
	if (o != null) {
	    for (int i = 0; i < size; i++)
	        if (o.equals(queue[i]))
	           return i;
	}
	return -1;
}

remove方法

	public boolean remove(Object o) {
        int i = indexOf(o);
        if (i == -1)
            return false;
        else {
            removeAt(i);
            return true;
        }
    }
    boolean removeEq(Object o) {
        for (int i = 0; i < size; i++) {
            if (o == queue[i]) {
                removeAt(i);
                return true;
            }
        }
        return false;
    }
    
    
	@SuppressWarnings("unchecked")
    E removeAt(int i) {
        // assert i >= 0 && i < size;
        modCount++;
        int s = --size;
        if (s == i) // removed last element
            queue[i] = null;
        else {
        	/** 删除下标i的元素:将最后一个元素替换到位置i,然后调整 **/
            E moved = (E) queue[s];//末尾元素
            queue[s] = null;
            siftDown(i, moved);//向下调整
            /** 先向下调整,如果queue[i] == moved 说明最后一个元素moved是
              下标为i的子树的最大值,有可能moved会大于父节点所以还要向上
              调整;否者说明moved一定小于父节点,所以不必向上调整。**/
            if (queue[i] == moved) {
                siftUp(i, moved);
                if (queue[i] != moved)
                    return moved;
            }
        }
        return null;
    }

remove和removeEq的区别是:remove删除equals为真的元素,removeEq删除==为真的元素。

最后就是扩容了。默认初始容量是11。当添加元素时如果数组已满就会进行扩容,调用grow方法。

private void grow(int minCapacity) {
        int oldCapacity = queue.length;
        // Double size if small; else grow by 50%
        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
                                         (oldCapacity + 2) :
                                         (oldCapacity >> 1));
        // overflow-conscious code
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        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;
    }

参数minCapacity:扩容后的最小容量
如果当前容量小于64,扩容后的容量为2capacity+2;
否则为 1.5
capacity。
如果minCapacity > MAX_ARRAY_SIZE 容量为Integer.MAX_VALUE。
如果minCapacity < 0,说明当前容量为Integer.MAX_VALUE,并且还需要更大的空间,这是会抛出OutOfMemoryError()。

基本就这些。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值