ArrayDeque
Stack已经不被推荐了,现在使用栈和队列的时候推荐ArrayDeque。
Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization, they do not support concurrent access by multiple threads. Null elements are prohibited. This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.
Deque接口的可调整数组实现。数组deque没有容量限制;它们会在必要时增长以支持使用。它们不是线程安全的;在没有外部同步的情况下,它们不支持多个线程的并发访问。禁止使用空元素。当使用该类作为堆栈时,它可能比Stack快,当使用该类作为队列时,它可能比LinkedList快。
Most ArrayDeque operations run in amortized constant time. Exceptions include remove, removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk operations, all of which run in linear time.
大多数ArrayDeque操作运行在平摊常量时间内。异常包括remove、removeFirstOccurrence、removeLastOccurrence、contains、iterator.remove()和bulk操作,所有这些操作都在线性时间内运行。
The iterators returned by this class’s iterator method are fail-fast: If the deque is modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will generally throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
这个类的迭代器方法返回的迭代器是快速失败的:如果在创建迭代器后的任何时间修改了deque,除了通过迭代器自己的remove方法,其他任何方式迭代器通常都会抛出ConcurrentModificationException。因此,在面对并发修改时,迭代器快速而干净地失败,而不是在未来不确定的时间冒任意的、不确定的行为的风险。
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.注意,不能保证迭代器快速失败的行为,因为一般来说,在存在非同步并发修改的情况下,不可能做出任何硬保证。快速失败迭代器会抛出ConcurrentModificationException异常。因此,编写依赖此异常来保证正确性的程序是错误的:迭代器的快速失败行为应该只用于检测bug。
该类及其迭代器实现了集合和迭代器接口的所有可选方法。
ArrayDeque是由会进行扩容的数组实现的,线程不安全,且不支持使用null。
参数
//存放元素的数组,长度永远为2的幂,如果数组满了就会立刻扩容
transient Object[] elements; // non-private to simplify nested class access
//头节点的索引
transient int head;
//元素被添加的位置的索引
transient int tail;
//最小容量,一定2的幂
private static final int MIN_INITIAL_CAPACITY = 8;
构造函数
/**
* Constructs an empty array deque with an initial capacity
* sufficient to hold 16 elements.
*/
public ArrayDeque() {
elements = new Object[16];
}
不指定,默认为16的长度。
/**
* Constructs an empty array deque with an initial capacity
* sufficient to hold the specified number of elements.
*
* @param numElements lower bound on initial capacity of the deque
*/
public