集合:Queue
Queue:Deque,PriorityQueue,PriorityBlockingQueue,ArrayBlockingQueue
Queue用于模拟队列这种数据结构。队列通常是指“先进先出(FIFO)”的容器。队列的头部保存在队列中存放时间最长的元素,尾部保存存放时间最短的元素。新元素插入到队列的尾部,取出元素会返回队列头部的元素。通常,队列不允许随机访问队列中的元素。
1. PriorityQueue:无边界,支持优先级队列实现类,非线程安全。按源码注释:添加修改等操作的时间复杂度为O(log(n));底层用数组实现,初始容量为11, 队列优先级可以根据自定义Comparator,不定义将使用自然排序。
/**
* Increases the capacity of the array.
*
* @param minCapacity the desired minimum capacity
*/
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);
}
扩容规则为: int newCapacity = oldCapacity + ((oldCapacity < 64) ?
(oldCapacity + 2) :
(oldCapacity >> 1));
原容量不足64时,容量+2,大于64时,新容量=旧容量+旧容量右移一位容量
@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;
}
新加元素定位时采用的是折半查找算法。删除元素同理
2. PriorityBlockingQueue:PriorityQueue的线程安全实现类。
3. ArrayBlockingQueue:有边界队列实现类,线程安全。一旦创建,容量不可改变。