Queue介绍
队列,先进先出。
Queue接口与List、Set同一级别,都是继承了Collection接口。
Queue使用
常用方法 | 解释 |
---|---|
offer(e) | 添加元素,成功为true,失败为false |
poll () | 返回队列头,出队列,队列空为null |
peek() | 返回队列头,不出队列,队列空为null |
Deque介绍
双端队列,可在两头入队和出队
Deque使用
当成单端队列使用
常用方法 | 解释 |
---|---|
offerLast(e) | 队列头添加元素,成功为true,失败为false |
pollFirst () | 返回队列头,出队列,队列空为null |
peekFirst() | 返回队列头,不出队列,队列空为null |
当成双端队列使用
常用方法 | 解释 |
---|---|
offerFirst(e) | 队列头添加元素,成功为true,失败为false |
pollFirst () | 返回队列头,出队列,队列空为null |
peekFirst() | 返回队列头,不出队列,队列空为null |
offerLast(e) | 队列尾添加元素,成功为true,失败为false |
pollLast() | 返回队列尾,出队列,队列空为null |
peekLast() | 返回队列尾,不出队列,队列空为null |
当成栈使用
方法 | 解释 |
---|---|
push(e) | 入栈,失败则抛出 illegalStateException |
peek() | 返回栈顶值,失败抛出NoSuchElementException |
pop() | 出栈,返回栈顶值,失败抛出NoSuchElementException |
ArrayDeque的介绍
Deque接口的可调整大小的数组实现。
- 没有容量限制,按需增长。
- 非线程安全
- 禁止null值
- 当成栈使用时,比Stack类快
- 当成单边队列使用时,比LinkedList快
底层是一个object数组,初始容量为8。head和tail属性控制队列头和队列尾。
transient Object[] elements; // non-private to simplify nested class access
/**
* The index of the element at the head of the deque (which is the
* element that would be removed by remove() or pop()); or an
* arbitrary number equal to tail if the deque is empty.
*/
transient int head;
/**
* The index at which the next element would be added to the tail
* of the deque (via addLast(E), add(E), or push(E)).
*/
transient int tail;
/**
* The minimum capacity that we'll use for a newly created deque.
* Must be a power of 2.
*/
private static final int MIN_INITIAL_CAPACITY = 8;
ArrayDeque的使用
调用Deque接口中的方法即可
LinkedList的介绍
实现了List和Deque接口的双端链表实现类。接受null值。线程非安全。
核心结构是内部类Node
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
LinkedList的使用
调用deque或者List中的接口方法即可使用。