Queue接口定義了隊列數據結構,元素是有序的(按插入順序),先進先出。Queue接口相關的部分UML類圖如下:
DeQueue
DeQueue(Double-ended queue)為接口,繼承了Queue接口,創建雙向隊列,靈活性更強,可以前向或后向迭代,在隊頭隊尾均可心插入或刪除元素。它的兩個主要實現類是ArrayDeque和LinkedList。
ArrayDeque (底層使用循環數組實現雙向隊列)
1.1 創建
public ArrayDeque() {
// 默認容量為16
elements = new Object[16];
}
public ArrayDeque(int numElements) {
// 指定容量的構造函數
allocateElements(numElements);
}
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;// 最小容量為8
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
// 如果要分配的容量大于等于8,擴大成2的冪(是為了維護頭、尾下標值);否則使用最小容量8
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
elements = new Object[initialCapacity];
}
1.2 add操作
add(E e) 調用 addLast(E e) 方法:
public void addLast(E e) {
if (e == null)
throw new NullPointerException("e == null");
elements[tail] = e; // 根據尾索引,添加到尾端
// 尾索引+1,并與數組(length - 1)進行取‘&’運算,因為length是2的冪,所以(length-1)轉換為2進制全是1,
// 所以如果尾索引值 tail 小于等于(length - 1),那么‘&’運算后仍為 tail 本身;如果剛好比(length - 1)大1時,
// ‘&’運算后 tail 便為0(即回到了數組初始位置)。正是通過與(length - 1)進行取‘&’運算來實現數組的雙向循環。
// 如果尾索引和頭索引重合了,說明數組滿了,進行擴容。
if ((tail = (tail + 1) & (elements.length - 1)) == head)
doubleCapacity();// 擴容為原來的2倍
}
addFirst(E e) 的實現:
public void addFirst(E e) {
if (e == null)
throw new NullPointerException("e == null");
// 此處如果head為0,則-1(1111 1111 1111 1111 1111 1111 1111 1111)與(length - 1)進行取‘&’運算,結果必然是(length - 1),即回到了數組的尾部。
elements[head = (head - 1) & (elements.length - 1)] = e;
// 如果尾索引和頭索引重合了,說明數組滿了,進行擴容
if (head == tail)
doubleCapacity();
}
1.3 remove操作
remove()方法最終都會調對應的poll()方法:
public E poll() {
return pollFirst();
}
public E pollFirst() {
int h = head;
@SuppressWarnings("unchecked") E result = (E) elements[h];
// Element is null if deque empty
if (result == null)
return null;
elements[h] = null; // Must null out slot
// 頭索引 + 1
head = (h + 1) & (elements.length - 1);
return result;
}
public E pollLast() {
// 尾索引 - 1
int t = (tail - 1) & (elements.length - 1);
@SuppressWarnings("unchecked") E result = (E) elements[t];
if (result == null)
return null;
elements[t] = null;
tail = t;
return result;
}
PriorityQueue(底層用數組實現堆的結構)
優先隊列跟普通的隊列不一樣,普通隊列是一種遵循FIFO規則的隊列,拿數據的時候按照加入隊列的順序拿取。 而優先隊列每次拿數據的時候都會拿出優先級最高的數據。
優先隊列內部維護著一個堆,每次取數據的時候都從堆頂拿數據(堆頂的優先級最高),這就是優先隊列的原理。
2.1 add,添加方法
public boolean add(E e) {
return offer(e); // add方法內部調用offer方法
}
public boolean offer(E e) {
if (e == null) // 元素為空的話,拋出NullPointerException異常
throw new NullPointerException();
modCount++;
int i = size;
if (i >= queue.length) // 如果當前用堆表示的數組已經滿了,調用grow方法擴容
grow(i + 1); // 擴容
size = i + 1; // 元素個數+1
if (i == 0) // 堆還沒有元素的情況
queue[0] = e; // 直接給堆頂賦值元素
else // 堆中已有元素的情況
siftUp(i, e); // 重新調整堆,從下往上調整,因為新增元素是加到最后一個葉子節點
return true;
}
private void siftUp(int k, E x) {
if (comparator != null) // 比較器存在的情況下
siftUpUsingComparator(k, x); // 使用比較器調整
else // 比較器不存在的情況下
siftUpComparable(k, x); // 使用元素自身的比較器調整
}
private void siftUpUsingComparator(int k, E x) {
while (k > 0) { // 一直循環直到父節點還存在
int parent = (k - 1) >>> 1; // 找到父節點索引,等同于(k - 1)/ 2
Object e = queue[parent]; // 獲得父節點元素
// 新元素與父元素進行比較,如果滿足比較器結果,直接跳出,否則進行調整
if (comparator.compare(x, (E) e) >= 0)
break;
queue[k] = e; // 進行調整,新位置的元素變成了父元素
k = parent; // 新位置索引變成父元素索引,進行遞歸操作
}
queue[k] = x; // 新添加的元素添加到堆中
}
2.2 poll,出隊方法
public E poll() {
if (size == 0)
return null;
int s = --size; // 元素個數-1
modCount++;
E result = (E) queue[0]; // 得到堆頂元素
E x = (E) queue[s]; // 最后一個葉子節點
queue[s] = null; // 最后1個葉子節點置空
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); // 使用元素自身的比較器調整
}
private void siftDownUsingComparator(int k, E x) {
int half = size >>> 1; // 只需循環節點個數的一般即可
while (k < half) {
int child = (k << 1) + 1; // 得到父節點的左子節點索引,即(k * 2)+ 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; // 最后一個葉子節點添加到合適的位置
}
2.3 remove,刪除隊列元素
public boolean remove(Object o) {
int i = indexOf(o); // 找到數據對應的索引
if (i == -1) // 不存在的話返回false
return false;
else { // 存在的話調用removeAt方法,返回true
removeAt(i);
return true;
}
}
private E removeAt(int i) {
modCount++;
int s = --size; // 元素個數-1
if (s == i) // 如果是刪除最后一個葉子節點
queue[i] = null; // 直接置空,刪除即可,堆還是保持特質,不需要調整
else { // 如果是刪除的不是最后一個葉子節點
E moved = (E) queue[s]; // 獲得最后1個葉子節點元素
queue[s] = null; // 最后1個葉子節點置空
siftDown(i, moved); // 從上往下調整
if (queue[i] == moved) { // 如果從上往下調整完畢之后發現元素位置沒變,從下往上調整
siftUp(i, moved); // 從下往上調整
if (queue[i] != moved)
return moved;
}
}
return null;
}
先執行 siftDown() 下濾過程:
再執行 siftUp() 上濾過程:
2.4 總結和同步的問題
1、jdk內置的優先隊列PriorityQueue內部使用一個堆維護數據,每當有數據add進來或者poll出去的時候會對堆做從下往上的調整和從上往下的調整。
2、PriorityQueue不是一個線程安全的類,如果要在多線程環境下使用,可以使用 PriorityBlockingQueue 這個優先阻塞隊列。其中add、poll、remove方法都使用 ReentrantLock 鎖來保持同步,take() 方法中如果元素為空,則會一直保持阻塞。