从名字就能看出来:
1. 实现了 Deque 接口。支持头部/尾部的插入/删除/读取操作。
2. 使用数组实现,如果容量不够,会自动扩容。
下面我们以 add 函数为入口,看一下源码:
public boolean add(E e) {
addLast(e);
return true;
}
public void addLast(E e) {
if (e == null)
throw new NullPointerException();
elements[tail] = e;
if ( (tail = (tail + 1) & (elements.length - 1)) == head)
doubleCapacity();
}
private void 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)
throw new IllegalStateException("Sorry, deque too big");
Object[] a = new Object[newCapacity];
System.arraycopy(elements, p, a, 0, r);
System.arraycopy(elements, 0, a, r, p);
elements = a;
head = 0;
tail = n;
}
从源码可以看出以下几点:
1. 默认的 add 是在队尾插入。符合日常生活排队的场景。
2. 不允许插入插入 null 。这样做好处是:获取元素的时候可以通过返回 null 来表示列表为空。
3. 不是单纯的通过数组实现队列,而是通过循环数组。这样做的好处是:提升空间利用率。当队列头部元素出队后,数组头部的空间可以重复利用。
4. 当数组容量不够时候,会将容量翻倍。最大容量是 int 的最大值(约等于 21 亿),超过这个值会溢出变成负数,就会抛出异常 了。
参考链接: