LinkedList类定义
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable{}
可以重点关注下Deque这个接口,最后介绍这个接口。
主要成员变量
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
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;
}
}
静态内部类Node是LinkedList的内部链表节点结构,包含了存储元素的item,以及前一个节点prev,后一个节点next。size代表节点数量,first是head节点,last是tail节点。
构造方法
/**
* Constructs an empty list.
*/
public LinkedList() {
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
主要有两个构造方法,第一个是建立一个空的list,第二个是用Collection参数来建立list。
主要方法
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
添加一个元素到队尾,实质是新产生一个元素,然后修改其next prev指向,同时修改first和last指针,最后更新size和modCount
/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Links e as first element.
*/
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
这个方法是在队头添加元素,也是操作链表。
其他的poll remove addLast offer 等都是类似的,均是操作链表,更新size值和modCount,不再赘述。
Deque接口
先看看接口图
Deque继承了Queue,完整名称是double-ended-queue,双端队列,队头队尾均可以插入和删除元素,所以这样可以充当队列(FIFO)或者Stack(FILO),看看Deque的主要方法。
通过其中的几个方法的组合,我们就可以实现一个queue或一个stack。
需要注意一下方法的返回值。
需要注意的地方
LinkedList实现了Deque接口,可以当做queue或stack来使用,本身不是线程安全的,可以使用Collections.sychronizedList()方法来包装成线程安全的list。