1、LinkedList类的说明
在上篇我们分析了ArrayList的底层实现,知道了ArrayList底层是基于数组实现的,因此具有查找修改快而插入删除慢的特点。本篇介绍的LinkedList是List接口的另一种实现,它的底层是基于双向链表实现的,因此它具有插入删除快而查找修改慢的特点,此外,通过对双向链表的操作还可以实现队列和栈的功能。下面我们就来看看LinkedList是怎么样来实现的。
1.1 解释说明
* 双向链表是实现了List和Deque接口。实现了所有List的操作和允许值为Null。
*
* 所有的操作执行都与双向链表相似。操作索引将遍历整个链表,至于是从头开始遍历还是从尾部
* 开始遍历取决于索引的下标距离哪个比较近。
*
* 需要注意的是这个方法不是同步的方法,需要同步的应用(ConcurrentLinkedDeque高效的队列),如果多个
* 线程同时操作LinkedList实例和至少有一个线程修改list的结构,必须在外部加同步操作。关于
* 结构性操作可以看前面的HashMap的介绍。这个同步操作通常是压缩在某些对象头上面。(synchronized
* 就是存储在对象头上面。)
*
* 如果对象头不存在这样的对象,这个列表应该使用{@link Collections#synchronizedList Collections.synchronizedList}工具
* 来封装,这个操作最好是在创建List之前完成,防止非同步的操作。
* List list = Collections.synchronizedList(new ArrayList(...));
* 但是一般不用这个方法,而是用JUC包下的ConcurrentLinkedDeque更加高效,(因为这个底层采用的是CAS操作)
*
* 快速失败机制(...好像在集合容器下面都有这个机制来抛出异常...)
* 当一个list被多个线程成同时修改的时候会抛出异常。但是不能用来保证线程安全。
* 所以在多线程环境下,还是要自己加锁或者采用JUC包下面的方法来保证线程安全,
* 而不能依靠fail-fast机制抛出异常,这个方法只是用来检测bug。
整个说明文档其实是跟ArrayList差不多,只不过是他们的底层实现的数据结构不一样而已,可以参考对比ArrayList。
1.2 数据结构
其中的节点Node主要由三部分组成;pre:前驱引用,ele1:节点信息,next:后驱引用。还有两个引用,分别指向头结点的first和指向尾结点的last.
2、方法字段
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
//元素个数
transient int size = 0;
/**
* 指向第一个节点
*
*/
transient Node<E> first;
/**
* 指向最后一个节点
*/
transient Node<E> last;
.
.
.
.
}
LinedList的字段比较少,多添加了两个引用first和last用来指向头尾节点,和一个size用来存储节点的个数,这样当计算元素个数的时候,只需要O(1)的时间复杂度。
3、关键方法
构造函数
/**
* 空的构造函数
*/
public LinkedList() {
}
/**
* 包含一个数组的构造函数,链表中的顺序按照集合中的元素顺序进行插入
*
* @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);//这里调用了addAll(),就是插入所有元素
}
有两个构造函数,一个是初始化一个空的实例,另外一个是传入一个集合进行初初始化。在初始化的时候主要调用了addAll()方法,那么这个addAll()方法是怎么样添加元素的呢。
addAll(int index, Collection<? extends E> c)
/**
* 插入给定集合的元素,从指定的index开始插入
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();//为什么要将集合转为数组?????
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;//前驱和后继引用
if (index == size) {//如果插入的位置刚好在最后位置
succ = null;//后继用用置位空
pred = last;//前驱为last所引用的尾结点
} else {
succ = node(index);//寻找插入的节点位置
pred = succ.prev;//保存该节点的前驱
}
for (Object o : a) {//循环插入每个节点
@SuppressWarnings("unchecked") E e = (E) o;//向下转型
Node<E> newNode = new Node<>(pred, e, null);//生成一个新节点
if (pred == null)//前驱为空,表示在第一个位置插入
first = newNode;
else//否则在index前面插入新节点
pred.next = newNode;
pred = newNode;//前驱为新节点
}
if (succ == null) {//后继为空
last = pred;//在末尾插入
} else {
pred.next = succ;//否则链接最后的节点
succ.prev = pred;
}
size += numNew;//节点个数增加
modCount++;//结构性修改
return true;
}
在addALL©中主要是调用了上面的这个方法
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
这个方法首先是将集合转为数组,那么为什么要这样子做呢,我们来看看toArray()方法
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list
* in proper sequence
*/
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
其实从方法中我并没有理解到它是有什么关键的作用,主要是在解释说明的上面The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array.
我的理解是转为toArray能保证在多线程的环境下不会被其他线程所修改,从而保证了数据的安全性。但是从方法中不知道是怎么实现的。
之后的方法过程注释已经写的很清楚了。
整体的插入过程可以用下图来解释
1、找到节点
找到下标为Index的节点标记为succ,找到它的前驱节点标记为pred,
2、插入新节点
3、移动指向
4、循环执行2 3 步骤
linkFirst(E e)
/**
* 在头部插入一个新节点
*/
private void linkFirst(E e) {
final Node<E> f = first;//1、创建一个引用
final Node<E> newNode = new Node<>(null, e, f);//2、创建新节点,它的下一个节点为当前的头结点
first = newNode;//3、头引用指向新节点
if (f == null)//如果没有头结点,只有尾结点
last = newNode;//新节点为尾结点
else
f.prev = newNode;//4、否则之前的头结点的前引用指向新节点
size++;
modCount++;
}
具体步骤如下所示
linkLast(E e)
/**
*在尾部插入一个新节点
*/
void linkLast(E e) {
final Node<E> l = last;//创建一个指向尾部的指针
final Node<E> newNode = new Node<>(l, e, null);//创建新节点,新节点的前一个节点为当前的尾结点
last = newNode;//last引用指向新节点
if (l == null)
first = newNode;
else
l.next = newNode;//当前尾结点的前引用指向新的尾结点
size++;
modCount++;
}
过程与在头部插入类似
linkBefore(E e, Node succ)
/**
* 在某个节点之前插入一个新节点
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;//找到该节点的前驱
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)//前驱为空
first = newNode;//新节点为第一个节点
else
pred.next = newNode;//否则在前面插入
size++;
modCount++;
}
unlink(Node x)
/**
* 删除某个非空节点
*/
E unlink(Node<E> x) {
// assert x != null;
//1、找到保存节点信息,找到前置和后继节点
final E element = x.item;//保存要删除节点的信息
final Node<E> next = x.next;//保存后继节点
final Node<E> prev = x.prev;//保存前置节点
//2、修改前置指针
if (prev == null) {//如果前置为空,
first = next;//则后置节点为第一个节点
} else {
prev.next = next;//否则将前置节点的下一个节点指向后继
x.prev = null;//将要删除节点的引用置空
}
//3、修改后继指针
if (next == null) {//后继为空,则前置节点为最后节点
last = prev;
} else {
next.prev = prev;//否则后继节点的引用指向前置
x.next = null;//将要删除节点的引用置空
}
//4、将节点置空,方便GC
x.item = null;//节点置空,GC
size--;
modCount++;
return element;
}
1、找到保存节点信息,找到前置和后继节点
2、修改前置指针
3、修改后继指针
4、将节点置空,方便GC
get(),set(),add(),remove()
// Positional Access Operations
/**
* 获取指定位置的元素
*/
public E get(int index) {
checkElementIndex(index);//检查下标
return node(index).item;//索引节点
}
/**
* 修改下标为index的节点
*/
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
/**
* 在指定位置插入元素
*/
public void add(int index, E element) {
checkPositionIndex(index);//检查下标
if (index == size)//如果index刚好为之后一个位置
linkLast(element);//插入最后面
else
linkBefore(element, node(index));//插在指定位置前面
}
/**
* 删除指定位置的元素
*/
public E remove(int index) {
checkElementIndex(index);//检查下标
return unlink(node(index));
}
增删改查都是基于前面的链表操作(link和unlink)来实现的
其他一些操作
/**
* 返回第一个节点
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
/**
* 返回最后一个节点
*/
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
/**
* 删除第一个节点
*
*/
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* 删除最后一个节点
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* 在第一个节点之前插入一个新节点
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* 在最后一个节点之后插入一个新节点
*/
public void addLast(E e) {
linkLast(e);
}
/**
*
* 如果包含该节点,则返回该节点的索引下标
*
*
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* 返回节点个数
*/
public int size() {
return size;
}
/**
* 调用add是在最后链接的
*/
public boolean add(E e) {
linkLast(e);
return true;
}
node(int index)
/**
* 返回指定位置的节点
*/
Node<E> node(int index) {
if (index < (size >> 1)) { //如果index在前半段
Node<E> x = first;//从头开始找
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {//在后半段
Node<E> x = last;
for (int i = size - 1; i > index; i--)//从后往前找
x = x.prev;
return x;
}
}
查找指定元素,这个方法用到一个小技巧,当检索的下标大于元素的一半,则从后往前找,小于一半则从前往后找
栈和队列的操作
/**
* 检索头结点元素
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* 与peek()作用一样
*/
public E element() {
return getFirst();
}
/**
* 删除并返回第一个节点
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* 与poll()作用一样
*/
public E remove() {
return removeFirst();
}
/**
* 在尾部添加节点与add()一样
*/
public boolean offer(E e) {
return add(e);
}
// Deque operations
/**
* 在头部插入节点
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
其实操作都一样,只是改个名字而已
4、总结
不管是单向队列还是双向队列还是栈,其实都是对链表的头结点和尾结点进行操作,它们的操作和linkBefore()和unlink()类似,只不过一个是对链表两端操作,一个是对链表中间操作。可以说这四个方法都是linkBefore()和unlink()方法的特殊情况,因此不难理解它们的内部实现,在此不多做介绍。到这里,我们对LinkedList的分析也即将结束,对全文中的重点做个总结:
- LinkedList是基于双向链表实现的,不论是增删改查方法还是队列和栈的实现,都可通过操作结点实现
- LinkedList无需提前指定容量,因为基于链表操作,集合的容量随着元素的加入自动增加
- LinkedList删除元素后集合占用的内存自动缩小,无需像ArrayList一样调用trimToSize()方法
- LinkedList的所有方法没有进行同步,因此它也不是线程安全的,应该避免在多线程环境下使用
- 以上分析基于JDK1.8,其他版本会有些出入,因此不能一概而论