简单的看一下它特有的几个方法
boolean offer(E e) // insert the given element if possible
The methods that throw an exception for an empty queue are:
E element() // retrieve but do not remove the head element
E remove() // retrieve and remove the head element
E element() // retrieve but do not remove the head element
E remove() // retrieve and remove the head element
====
E peek() // retrieve but do not remove the head element
E poll() // retrieve and remove the head element
E poll() // retrieve and remove the head element
除了上面提到的两个方法在queue为空时调用会抛出异常,其他的比如peek,poll,都用null返回值来表示queue为空,所以不允许放入null值。
14.1. Using the Methods of Queue
这部分内容比较少,代码中使用了ArrayDeque,我们接下来就来看一下ArrayDeque的实现方法。
ArrayDeque类实现Queue接口。
对于数组实现的Deque来说,数据结构上比较简单,只需要一个存储数据的数组以及头尾两个索引即可。由于数组是固定长度的,所以很容易就得到数组的头和尾,那么对于数组的操作只需要移动头和尾的索引即可。
特别说明的是 ArrayDeque并不是一个固定大小的队列 , 每次队列满了以后就将队列容量扩大一倍(doubleCapacity()),因此加入一个元素总是能成功 ,而且也不会抛出一个异常。也就是说ArrayDeque是一个没有容量限制的队列。
同样继续性能的考虑,使用System.arraycopy复制一个数组比循环设置要高效得多。
ArrayDeque不是线程安全的 。
ArrayDeque不可以存取null元素,因为系统根据某个位置是否为null来判断元素的存在。
当作为栈使用时,性能比Stack好(Stack是线程安全类的原因?);当作为队列使用时,性能比LinkedList好。总结:
1. 两个重要的索引:head和tail
Java代码
- // 第一个元素的索引
- privatetransientint head;
- // 下个要添加元素的位置,为末尾元素的索引 + 1
- privatetransientint tail;
- public ArrayDeque() {
- elements = (E[]) new Object[ 16 ]; // 默认的数组长度大小
- }
- public ArrayDeque( int numElements) {
- allocateElements(numElements); // 需要的数组长度大小
- }
- public ArrayDeque(Collection<? extends E> c) {
- allocateElements(c.size()); // 根据集合来分配数组大小
- addAll(c); // 把集合中元素放到数组中
- }
3. 分配合适大小的数组
Java代码
- privatevoid allocateElements( int numElements) {
- int initialCapacity = MIN_INITIAL_CAPACITY;
- // 找到大于需要长度的最小的2的幂整数。
- // Tests "<=" because arrays aren't kept full.
- 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 = (E[]) new Object[initialCapacity];
- }
4. 扩容
Java代码
- // 扩容为原来的2倍。
- privatevoid doubleCapacity() {
- assert head == tail;
- int p = head;
- int n = elements.length;
- int r = n - p; // number of elements to the right of p
- int newCapacity = n << 1 ;
- if (newCapacity < 0 )
- thrownew IllegalStateException( "Sorry, deque too big" );
- Object[] a = new Object[newCapacity];
- // 既然是head和tail已经重合了,说明tail是在head的左边。
- System.arraycopy(elements, p, a, 0 , r); // 拷贝原数组从head位置到结束的数据
- System.arraycopy(elements, 0 , a, r, p); // 拷贝原数组从开始到head的数据
- elements = (E[])a;
- head = 0 ; // 重置head和tail为数据的开始和结束索引
- tail = n;
- }
- // 拷贝该数组的所有元素到目标数组
- private <T> T[] copyElements(T[] a) {
- if (head < tail) { // 开始索引大于结束索引,一次拷贝
- System.arraycopy(elements, head, a, 0 , size());
- } elseif (head > tail) { // 开始索引在结束索引的右边,分两段拷贝
- int headPortionLen = elements.length - head;
- System.arraycopy(elements, head, a, 0 , headPortionLen);
- System.arraycopy(elements, 0 , a, headPortionLen, tail);
- }
- return a;
- }
- 拷贝到a里面,并返回。
5. 添加元素
Java代码
- publicvoid addFirst(E e) {
- if (e == null )
- thrownew NullPointerException();
- elements[head = (head - 1 ) & (elements.length - 1 )] = e;
- if (head == tail) // head和tail不可以重叠
- doubleCapacity();
- }
- head-1为负值怎么办?
现在我们可以回答这个问题了,当head-1为负值时也不会有问题。我们看一下,加入head=0,现在head-1=-1,我们知道-1的二进制是全1,所以与mask相与后得到的还是mask,就是这里的length-1,刚好是我们需要调整的值,同时如果tail的值等于length-1,那么tail+1之后与mask相与的结果正好是0,也就是自动实现了循环。这里的length是2的n次方。如果不是2的n次方则不要用这种技巧。
- public void addLast(E e) {
- if (e == null )
- throw new NullPointerException();
- // tail位置是空的,把元素放到这。
- elements[tail] = e;
- if ( (tail = (tail + 1 ) & (elements.length - 1 )) == head)
- doubleCapacity();
- }
- public boolean offerFirst(E e) {
- addFirst(e);
- return true ;
- }
- public boolean offerLast(E e) {
- addLast(e);
- return true ;
- }
6.
删除元素
删除首尾元素:
Java代码
- public E removeFirst() {
- E x = pollFirst();
- if (x == null )
- throw new NoSuchElementException();
- return x;
- }
- public E removeLast() {
- E x = pollLast();
- if (x == null )
- throw new NoSuchElementException();
- return x;
- }
- public E pollFirst() {
- int h = head;
- E result = elements[h]; // Element is null if deque empty
- if (result == null )
- return null ;
- // 表明head位置已为空
- elements[h] = null ; // Must null out slot
- head = (h + 1 ) & (elements.length - 1 ); // 处理临界情况(当h为elements.length - 1时),与后的结果为0。
- return result;
- }
- public E pollLast() {
- int t = (tail - 1 ) & (elements.length - 1 ); // 处理临界情况(当tail为0时),与后的结果为elements.length - 1。
- E result = elements[t];
- if (result == null )
- return null ;
- elements[t] = null ;
- tail = t; // tail指向的是下个要添加元素的索引。
- return result;
- }
删除指定元素:
Java代码
- public boolean removeFirstOccurrence(Object o) {
- if (o == null )
- return false ;
- int mask = elements.length - 1 ;
- int i = head;
- E x;
- while ( (x = elements[i]) != null ) {
- if (o.equals(x)) {
- delete(i);
- return true ;
- }
- i = (i + 1 ) & mask; // 从头到尾遍历
- }
- return false ;
- }
- public boolean removeLastOccurrence(Object o) {
- if (o == null )
- return false ;
- int mask = elements.length - 1 ;
- int i = (tail - 1 ) & mask; // 末尾元素的索引
- E x;
- while ( (x = elements[i]) != null ) {
- if (o.equals(x)) {
- delete(i);
- return true ;
- }
- i = (i - 1 ) & mask; // 从尾到头遍历
- }
- return false ;
- }
- private boolean delete( int i) {
-
- checkInvariants();
- final E[] elements = this .elements;
- final int mask = elements.length - 1 ;
- final int h = head;
- final int t = tail;
- final int front = (i - h) & mask; // i前面的元素个数
- final int back = (t - i) & mask; // i后面的元素个数
- // Invariant: head <= i < tail mod circularity
- if (front >= ((t - h) & mask)) // i不在head和tail之间
- throw new ConcurrentModificationException();
- // Optimize for least element motion
- if (front < back) { // i的位置靠近head,移动开始的元素,返回false。
- if (h <= i) {
- System.arraycopy(elements, h, elements, h + 1 , front);
- } else { // Wrap around
- System.arraycopy(elements, 0 , elements, 1 , i);
- elements[ 0 ] = elements[mask]; // 处理边缘元素
- System.arraycopy(elements, h, elements, h + 1 , mask - h);
- }
- elements[h] = null ;
- head = (h + 1 ) & mask; // head位置后移
- return false ;
- } else { // i的位置靠近tail,移动末尾的元素,返回true。
- if (i < t) { // Copy the null tail as well
- System.arraycopy(elements, i + 1 , elements, i, back);
- tail = t - 1 ;
- } else { // Wrap around
- System.arraycopy(elements, i + 1 , elements, i, mask - i);
- elements[mask] = elements[ 0 ];
- System.arraycopy(elements, 1 , elements, 0 , t);
- tail = (t - 1 ) & mask;
- }
- return true ;
- }
- }
![](https://app.yinxiang.com/shard/s21/res/a66fbc33-dd75-470f-a282-ff547d33c7aa.png)
7.
获取元素
Java代码
- public E getFirst() {
- E x = elements[head];
- if (x == null )
- throw new NoSuchElementException();
- return x;
- }
- public E getLast() {
- E x = elements[(tail - 1 ) & (elements.length - 1 )]; // 处理临界情况(当tail为0时),与后的结果为elements.length - 1。
- if (x == null )
- throw new NoSuchElementException();
- return x;
- }
return elements[head]; // elements[head] is null if deque empty
}
public E peekLast() {
return elements[(tail - 1 ) & (elements.length - 1 )];
}
这里面我们发现了一些与位运算有关的操作,比较有意思。比如对一个4个比特位的数来说,-4的二进制补码就是1100,我们把它与它的掩码相与,结果为0100,也就是4,这也正说明了减去一个数与加上一个它的补的关系,这个放到数轴上更加容易理解。其他比如(num&(num-1))==0,说明num是2的n次方等等。
10.
集合方法
Java代码
- public int size() {
- return (tail - head) & (elements.length - 1 ); // 和elements.length - 1进行与操作是为了处理当tail < head时的情况。
- }
- public boolean isEmpty() {
- return head == tail; // tail位置的元素一定为空,head和tail相等,也为空。
- }
- public void clear() {
- int h = head;
- int t = tail;
- if (h != t) { // clear all cells
- head = tail = 0 ; // 重置首尾索引
- int i = h;
- int mask = elements.length - 1 ;
- do {
- elements[i] = null ; // 清除元素
- i = (i + 1 ) & mask;
- } while (i != t);
- }
- }
- public Object[] toArray() {
- return copyElements( new Object[size()]);
- }
- public <T> T[] toArray(T[] a) {
- int size = size();
- if (a.length < size) // 目标数组大小不够
- a = (T[])java.lang.reflect.Array.newInstance(
- a.getClass().getComponentType(), size); // 利用反射创建类型为T,大小为size的数组。
- yElements(a); // 拷贝所有元素到目标数组。
- if (a.length > size)
- a[size] = null ; // 结束标识
- return a;
- }
11.
Object方法
Java代码
- public ArrayDeque<E> clone() {
- try {
- ArrayDeque<E> result = (ArrayDeque<E>) super .clone();
- result.elements = Arrays.copyOf(elements, elements.length); // 深度复制。
- return result;
- } catch (CloneNotSupportedException e) {
- throw new AssertionError();
- }
- }