Java容器解析系列(7) ArrayDeque 详解
ArrayDeque,从名字上就可以看出来,其是通过数组实现的双端队列,我们先来看其源码:
/**
有自动扩容机制;
不是线程安全的;
不允许添加null;
作为栈使用时比java.util.Stack快;
作为队列使用时比LinkedList快; 支持fast-fail;
* @since 1.6
*/
public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable {
// 元素数组;
// 数组大小永远是2的n次方;
// 保证所有的没有元素的位置,其值为null;
// 关于这里的数组大小为什么要求是2的n次方,后面会具体解释
private transient E[] elements;
// 头指针和尾指针
private transient int head;
private transient int tail;
// 最小容量
private static final int MIN_INITIAL_CAPACITY = 8;
// ****** Array allocation and resizing utilities ******
// 找到<=指定元素的2的n次方的数作为队列容量大小,并分配数组空间
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// 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];
}
// 将队列的容量翻倍,只在队列满时(也就是head == tail成立的时候)调用;
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 = (E[]) a;
head = 0;
tail = n;
}
// 复制本地元素到指定数组中,供toArray()调用
private <T> T[] copyElements(T[] a) {
if (head < tail) {
System.arraycopy(elements, head, a, 0, size());
} else if (head > tail) {
int headPortionLen = elements.length - head;
System.arraycopy(elements, head, a, 0, headPortionLen);
System.arraycopy(elements, 0, a, headPortionLen, tail);
}
return a;
}
// 默认大小为16
public ArrayDeque() {
elements = (E[]) new Object[16];
}
// 指定队列容量,实际队列的容量可能不是指定的数,因为队列容量必须为2的n次方
public ArrayDeque(int numElements) {
allocateElements(numElements);
}
public ArrayDeque(Collection<? extends E> c) {
allocateElements(c.size());
addAll(c);
}
// 重要的是addFirst(),addLast(),pollFirst(),pollLast()这4个方法,其他的方法都是基于这4个方法
// 添加新元素到头部,头指针-1
// 时间复杂度:O(1)
public void addFirst(E e) {
// 不允许添加null
if (e == null)
throw new NullPointerException();
// 因为 elements.length 为 2 的n次方,表达式(head - 1) & (elements.length - 1) 与 (head - 1) % elments.length相等,且前者效率比后者高(位运算效率比取模高)
// 这里的elements.length - 1也可以成称为掩码(mask)
elements[head = (head - 1) & (elements.length - 1)] = e;
// 如果添加元素导致队列满了,扩容
if (head == tail)
doubleCapacity();
}
// 添加新元素到尾部,尾指针+1
// 时间复杂度:O(1)
public void addLast(E e) {
// 不允许添加null
if (e == null)
throw new NullPointerException();
elements[tail] = e;
// 因为 elements.length 为 2 的n次方,表达式(tail + 1) & (elements.length - 1) 与 (head + 1) % elments.length相等
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;
}
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;
}
// 移除队头
// 时间复杂度:O(1)
public E pollFirst() {
int h = head;
E result = elements[h]; // Element is null if deque empty
// 证明队列是空的(ArrayDeque保证所有的没有元素的位置,其值为null)
if (result == null)
return null;
// 保证没有元素的地方值为null,且保证GC能正常回收
elements[h] = null; // Must null out slot
// 头指针右移
head = (h + 1) & (elements.length - 1);
return result;
}
// 移除队尾
// 时间复杂度:O(1)
public E pollLast() {
int t = (tail - 1) & (elements.length - 1);
E result = elements[t];
// 队列是空的
if (result == null)
return null;
elements[t] = null;
// 尾指针左移
tail = t;
return result;
}
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)];
if (x == null)
throw new NoSuchElementException();
return x;
}
public E peekFirst() {
return elements[head]; // elements[head] is null if deque empty
}
public E peekLast() {
return elements[(tail - 1) & (elements.length - 1)];
}
// 时间复杂度O(n)
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;
}
// 时间复杂度O(n)
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;
}
// *** Queue methods ***
public boolean add(E e) {
addLast(e);
return true;
}
public boolean offer(E e) {
return offerLast(e);
}
public E remove() {
return removeFirst();
}
public E poll() {
return pollFirst();
}
public E element() {
return getFirst();
}
public E peek() {
return peekFirst();
}
// *** Stack methods ***
public void push(E e) {
addFirst(e);
}
public E pop() {
return removeFirst();
}
private void checkInvariants() {
assert elements[tail] == null;
assert head == tail ? elements[head] == null
: (elements[head] != null && elements[(tail - 1) & (elements.length - 1)] != null);
assert elements[(head - 1) & (elements.length - 1)] == null;
}
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;
final int back = (t - i) & mask;
// Invariant: head <= i < tail mod circularity
if (front >= ((t - h) & mask))
throw new ConcurrentModificationException();
// Optimize for least element motion
if (front < back) {
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;
return false;
} else {
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;
}
}
// *** Collection Methods ***
public int size() {
return (tail - head) & (elements.length - 1);
}
public boolean isEmpty() {
return head == tail;
}
public Iterator<E> iterator() {
return new DeqIterator();
}
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
private class DeqIterator implements Iterator<E> {
private int cursor = head;
private int fence = tail;
private int lastRet = -1;
public boolean hasNext() {
return cursor != fence;
}
public E next() {
if (cursor == fence)
throw new NoSuchElementException();
E result = elements[cursor];
// This check doesn't catch all possible comodifications,
// but does catch the ones that corrupt traversal
if (tail != fence || result == null)
throw new ConcurrentModificationException();
lastRet = cursor;
cursor = (cursor + 1) & (elements.length - 1);
return result;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (delete(lastRet)) { // if left-shifted, undo increment in next()
cursor = (cursor - 1) & (elements.length - 1);
fence = tail;
}
lastRet = -1;
}
}
// 反向迭代器,犹如godv的那支箭。。。
private class DescendingIterator implements Iterator<E> {
/*
* This class is nearly a mirror-image of DeqIterator, using tail instead of
* head for initial cursor, and head instead of tail for fence.
*/
private int cursor = tail;
private int fence = head;
private int lastRet = -1;
public boolean hasNext() {
return cursor != fence;
}
public E next() {
if (cursor == fence)
throw new NoSuchElementException();
cursor = (cursor - 1) & (elements.length - 1);
E result = elements[cursor];
if (head != fence || result == null)
throw new ConcurrentModificationException();
lastRet = cursor;
return result;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (!delete(lastRet)) {
cursor = (cursor + 1) & (elements.length - 1);
fence = head;
}
lastRet = -1;
}
}
public boolean contains(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))
return true;
i = (i + 1) & mask;
}
return false;
}
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
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);
copyElements(a);
if (a.length > size)
a[size] = null;
return a;
}
// *** Object methods ***
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();
}
}
private static final long serialVersionUID = 2340985798034038923L;
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
// Write out size
s.writeInt(size());
// Write out elements in order.
int mask = elements.length - 1;
for (int i = head; i != tail; i = (i + 1) & mask)
s.writeObject(elements[i]);
}
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
// Read in size and allocate array
int size = s.readInt();
allocateElements(size);
head = 0;
tail = size;
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
elements[i] = (E) s.readObject();
}
}
从源码可以很容易的看出来:ArrayDeque本质为数组实现的循环队列,关于循环队列,请参考博客:循环队列(顺序队列)
增删的主要实现方法为addFirst(),addLast(),pollFirst(),pollLast()这4个方法,其他的方法都是调用这4个方法来实现功能,且其时间复杂度均为O(1)
ArrayDeque中的数组大小必须为2的n次方,这一点的解释可以参考上述源码中addFirst()和addLast()的注释,已经说得很清楚了
Java容器解析系列(7) ArrayDeque 详解的更多相关文章
- Java容器解析系列(11) HashMap 详解
本篇我们来介绍一个最常用的Map结构--HashMap 关于HashMap,关于其基本原理,网上对其进行讲解的博客非常多,且很多都写的比较好,所以.... 这里直接贴上地址: 关于hash算法: Ha ...
- Java容器解析系列(9) PrioriyQueue详解
PriorityQueue:优先级队列; 在介绍该类之前,我们需要先了解一种数据结构--堆,在有些书上也直接称之为优先队列: 堆(Heap)是是具有下列性质的完全二叉树:每个结点的值都 >= 其 ...
- Java容器解析系列(13) WeakHashMap详解
关于WeakHashMap其实没有太多可说的,其与HashMap大致相同,区别就在于: 对每个key的引用方式为弱引用; 关于java4种引用方式,参考java Reference 网上很多说 弱引用 ...
- Java容器解析系列(14) IdentityHashMap详解
IdentityHashMap,使用什么的跟HashMap相同,主要不同点在于: 数据结构:使用一个数组table来存储 key:value,table[2k] 为key, table[2k + 1] ...
- Java容器解析系列(17) LruCache详解
在之前讲LinkedHashMap的时候,我们说起可以用来实现LRU(least recent used)算法,接下来我看一下其中的一个具体实现-----android sdk 中的LruCache. ...
- Java容器解析系列(12) LinkedHashMap 详解
LinkedHashMap继承自HashMap,除了提供HashMap的功能外,LinkedHashMap还是维护一个双向链表(实际为带头结点的双向循环链表),持有所有的键值对的引用: 这个双向链表定 ...
- Java容器解析系列(0) 开篇
最近刚好学习完成数据结构与算法相关内容: Data-Structures-and-Algorithm-Analysis 想结合Java中的容器类加深一下理解,因为之前对Java的容器类理解不是很深刻, ...
- Java容器解析系列(10) Map AbstractMap 详解
前面介绍了List和Queue相关源码,这篇开始,我们先来学习一种java集合中的除Collection外的另一个分支------Map,这一分支的类图结构如下: 这里为什么不先介绍Set相关:因为很 ...
- Java容器解析系列(6) Queue Deque AbstractQueue 详解
首先我们来看一下Queue接口: /** * @since 1.5 */ public interface Queue<E> extends Collection<E> { / ...
随机推荐
- 微信小程序----wxss设置样式
一.wxml 界面结构wxmL比较容易理解,主要是由八大类基础组件构成: 一.视图容器(View Container): 二.基础内容(Basic Content) 组件名 说明 组件名 说明 vie ...
- laravel框架——验证码(第一种方法)
一.在框架根目录下下载图形验证码的组件 composer require gregwar/captcha=1.* 二.控制器代码 use Gregwar\Captcha\CaptchaBuilder; ...
- Codeforces 803C. Maximal GCD
题目链接:http://codeforces.com/contest/803/problem/C 中了若干trick之后才过... k个数的严格递增序列最小权值和就是${n*(n+1)/2}$,枚举这 ...
- ArcGIS Pro开发Web3D应用(3)——Server/Portal授权服务开发
1.整体环境搭建完成 WebAdaptor.DataStore.Portal for arcgis.arcgis server.arcgis pro都成功部署安装,不管是同服务器还是不同服务器,最好做 ...
- openssl 生成pfx
证书可以通过几种渠道获得, 可以购买, 可以使用IIS生成, 也可以使用Openssl这样的工具生成证书. 本篇文章主要介绍openssl生成pfx文件 首选去网关下载openssl 下载地址:htt ...
- NetBus —— 让你的 App 内部随处感知网络的变化
简介 NetBus 是一个实时监听网络状态的一个框架,接入简单.只需要几步就可以在 Activity 和 Fragment 以及其他要观测的类中很方便的收到网络状态变化的通知. 愿景 可以在 App ...
- [Web Service] Java Web Services Tutorial
两种主要的java web services api: JAX-WS 和JAX-RS. Java web service application 之间通过WSDL来交互. 有两种方法来书写java w ...
- Day 5内存管理,定义变量
昨日内容回顾 python的2种执行方式 交互式 写一句翻译一句 优点:能及时发现bug,及时调试 缺点:关即消失,不能保存 命令行式 优点:可以永久保存 缺点:无法及时看到结果 python3 c: ...
- JVM垃圾回收(三)- GC算法:基础
GC算法:基础 在介绍GC算法在实际场景中的实现之前,我们先定义一些必要的术语,以及GC算法的基本准则.具体的细节会因收集器的不同而稍有区别,但是基本上来说,所有的收集器会关注以下两个方面: 找出所有 ...
- WebvirtCloud安装(CentOS7)
1.安装依赖包wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repoyum -y install p ...