LinkedList源码分析
1、LinkedList体系结构
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
通过源码我们看到ListedList继承了AbstractSequentialList,并实现了List、Deque、Cloneable和Serializable接口。因此可以推断出ArrayList类底层是借助于数组来实现,LinkedList由于实现了Deque接口,则LinkedList类也具有双端队列的特性。
2、属性
几个属性如下:
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;
这里面有一个重要的类Node,我们看下其源码:
2.1 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;
}
}
从源码可以看到,Node类只定义了存储的元素、前一个元素的指向、后一个元素的指向,这就是双向链表的节点的定义,每个节点只知道自己的前一个节点和后一个节点。
还有一个有参的构造函数,从参数中可以看出,创建一个新的Node对象时要提供新Node对象的前指针、本节点的value和后指针。虽然JAVA中没有指针,但这里称为指针便于理解。如果你不习惯指针这一说话,可以理解为此节点的前一个元素的指向和 后一个元素的指向。
2.2 三个属性
LinkedList对象实例的大小
transient int size = 0;
头指针:指向LinkedList中的第一个元素
transient Node first;
尾指针:指向LinkedList中的最后一个元素
transient Node last;
既然上面的两个属性都是Node引用,也就是说,LinkedList类的实现就是依赖与Node节点来实现,因此有必要对此类进行一定的了解。
3、构造函数
通过源码看到LinkedList有两个构造函数,一个无参构造函数,一个有参构造函数。
3.1、无参构造函数
构造一个空的链表,源码:
/**
* Constructs an empty list.
*/
public LinkedList() {
}
3.2、有参构造函数
源码如下:
/**
* 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);
}
有参构造函数,参数是一个Collection,此函数首先调用无参构造函数构造了一个空对象,然后调用了addAll(c)方法,下面就先介绍这个方法,首先看方法源码:
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
而这个函数就是直接调用了addAll(int index, Collection),此方法源码如下:
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element
* from the specified collection
* @param c collection containing elements to be added to this list
* @return