LinkedList源码解析(基于JDK1.8)
LinkedList是基于双向循环链表(从源码中可以很容易看出)实现的,除了可以当做链表来操作外,它还可以当做栈、队列和双端队列来使用。
LinkedList同样是非线程安全的,只在单线程下适合使用。
LinkedList实现了Serializable接口,因此它支持序列化,能够通过序列化传输,实现了Cloneable接口,能被克隆。
继承了AbstractSequentialList,实现了List,Queue,Cloneable,Serializable,既可以当成列表使用,也可以当成队列,堆栈使用。
主要特点有:
1.线程不安全,不同步,如果需要同步需要使用
List list = Collections.synchronizedList(new LinkedList());
2.实现List接口,可以对它进行队列操作
3.实现Queue接口,可以当成堆栈或者双向队列使用
4.实现Cloneable接口,可以被克隆,浅拷贝
5.实现Serializable,可以被序列化和反序列化
参数说明
//链表的数据个数
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类LinkedList的静态内部类
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;
}
}
构造方法
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);//添加集合所有元素
}
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the specified
* collection's iterator. The behavior of this operation is undefined if
* the specified collection is modified while the operation is in
* progress. (Note that this will occur if the specified collection is
* this list, and it's nonempty.)
*
* 按照指定集合的迭代器返回的顺序,将指定集合中的所有元素追加到此列表的末尾。
* 如果在操作进行期间修改了指定的集合,则此操作的行为未定义。
* (请注意,如果指定的集合是此列表,并且它是非空的,则会发生这种情况。)
*
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
/**
* 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 {@code true} if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
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;
} else {
//查找到索引为index 的节点
succ = node(index);
//获取前一个节点
pred = succ.prev;
}
//遍历数组中的每个元素
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
//每次遍历都新建一个节点,每个节点存储都是a的值,
//该节点的前节点prev用来存储pred节点
//next置为null
Node<E> newNode = new Node<>(pred, e, null);
//如果前一个节点是null,那么第一个节点就是新的节点
if (pred == null)
//把当前节点设置为头节点
first = newNode;
else
//否则pred的next置为新节点
pred.next = newNode;
//最后把pred指向当前节点
pred = newNode;
}
//如果插入位置没有后续节点,也就是succ为null
if (succ == null) {
//最后一个节点也就是pred,刚刚插入的新节点
last = pred;
} else {
//加入所有元素之后的最后一个节点的下一个节点指向succ(后续元素)
pred.next = succ;
//插入位置的后续元素的上一个节点引用指向pred
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
/**
* Returns the (non-null) Node at the specified element index.
*/
//如果索引位置在后面一半,就从后往前遍历查找,否则从前往后遍历。
Node<E> node(int index) {
// assert isElementIndex(index);
// size>>1 表示除以2,相当于index小于size的一半
if (index < (size >> 1)) {
// 从前面开始遍历,取出first节点,因为中间过程引用会变化,所以不可直接操作first
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;
}
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
查找操作
/**
* Returns the first element in this list.
*
* 获取集合中的第一个元素
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
//保存第一个元素为f
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
/**
* Returns the last element in this list.
*
* 获取集合中的最后一个元素
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getLast() {
//保存第一个元素为l
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
/**
* Returns the element at the specified position in this list.
*
* 获取集合中指定索引的元素
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
//检查索引是否越界
checkElementIndex(index);
return node(index).item;
}
/**
* Returns the (non-null) Node at the specified element index.
*/
//如果索引位置在后面一半,就从后往前遍历查找,否则从前往后遍历。
Node<E> node(int index) {
// assert isElementIndex(index);
// size>>1 表示除以2,相当于index小于size的一半
if (index < (size >> 1)) {
// 从前面开始遍历,取出first节点,因为中间过程引用会变化,所以不可直接操作first
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;
}
}
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
*
*
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
//查找某一个元素的索引位置
public int indexOf(Object o) {
int index = 0;
// 如果需要查找null元素
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
// 查找元素不为空
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
//跟上面的indexOf差不多,就是倒过来查找
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
添加操作
/**
* 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;
//初始化新节点 prev 为空,item 为 e, next为 f (之前的第一个节点)
final Node<E> newNode = new Node<>(null, e, f);
//更新first节点
first = newNode;
//如果前面的第一个节点为空,那就说明那么就说明里面是空的,没有元素
if (f == null)
//最后一个元素也是新加入的元素
last = newNode;
else
//f的prev前置节点的引用更新为新的节点
f.prev = newNode;
size++;
modCount++;
}
/**
* 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;
}
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
*/
public void addLast(E e) {
linkLast(e);
}
/**
* Links e as last element.
*
* 链接e作为最后一个元素。
*/
void linkLast(E e) {
//指向链表的尾部
final Node<E> l = last;
//以尾部为前驱节点创建一个新节点
final Node<E> newNode = new Node<>(l, e, null);
//更新最后一个节点
last = newNode;
//如果之前的最后一个节点为空,说明链表是空的,就将新的节点指向first
if (l == null)
first = newNode;
else
//l的后置节点的引用跟新为新的节点
l.next = newNode;
size++;
modCount++;
}
/**
* Inserts the specified element at the specified position in this list.
* Shifts the element currently at that position (if any) and any
* subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
//在指定索引位置添加指定元素
public void add(int index, E element) {
//索引越界校验
checkPositionIndex(index);
//当索引等于链表长度,就说明直接在链表尾部添加元素
if (index == size)
linkLast(element);
else
//在某个节点前插入元素
linkBefore(element, node(index));
}
/**
* Inserts element e before non-null 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;
//如果当前所引的前置节点为空,就讲first更新为 新建节点
if (pred == null)
first = newNode;
else
//前置节点的next为 新建节点
pred.next = newNode;
size++;
modCount++;
}
/**
* Returns the (non-null) Node at the specified element index.
*/
//如果索引位置在后面一半,就从后往前遍历查找,否则从前往后遍历。
Node<E> node(int index) {
// assert isElementIndex(index);
// size>>1 表示除以2,相当于index小于size的一半
if (index < (size >> 1)) {
// 从前面开始遍历,取出first节点,因为中间过程引用会变化,所以不可直接操作first
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;
}
}
删除操作
/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
//删除第一个节点
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* Unlinks non-null first node f.
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
//获取元素
final E element = f.item;
//保存f的下一个节点
final Node<E> next = f.next;
//将元素值和元素的next节点置空,有利于GC
f.item = null;
f.next = null; // help GC
//首节点更新
first = next;
//如果首届点为空,链表就没有元素了,最后一个元素也就是空
if (next == null)
last = null;
else
//如果不为空,就将下一个结点的前置节点置为空
next.prev = null;
size--;
modCount++;
return element;
}
/**
* Removes and returns the last element from this list.
*
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
//移除为节点,并返回删除元素
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* Unlinks non-null last node l.
*/
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
//获取元素值
final E element = l.item;
//将元素的前置节点保存
final Node<E> prev = l.prev;
//将元素的前置和元素值置空
l.item = null;
l.prev = null; // help GC
//更新最后一个节点
last = prev;
//如果最后一个节点为空,那么链表为空
if (prev == null)
first = null;
else
//不为空,将前置节点的next置空
prev.next = null;
size--;
modCount++;
return element;
}
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If this list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns {@code true} if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return {@code true} if this list contained the specified element
*/
//移除一个指定元素(链表后续还有相同元素是不会移除的)
public boolean remove(Object o) {
//判断元素是否为空
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
/**
* Unlinks non-null node x.
*/
E unlink(Node<E> x) {
// assert x != null;
//保存元素的值和前后节点
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
//如果前置节点为空,那么头节点就是当前节点
if (prev == null) {
first = next;
} else {
//前一个节点的next置为next
prev.next = next;
//该节点的前节点置空
x.prev = null;
}
//如果后置节点为空,那么上一个节点就是最后一个节点
if (next == null) {
last = prev;
} else {
//next的上一个节点引用指向prev
next.prev = prev;
//被删除的节点的next置为空
x.next = null;
}
// item置空
x.item = null;
size--;
modCount++;
return element;
}
/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*/
//删除链表的所有元素
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
// 首节点和尾节点全部置null
first = last = null;
size = 0;
modCount++;
}
/**
* Removes the element at the specified position in this list. Shifts any
* subsequent elements to the left (subtracts one from their indices).
* Returns the element that was removed from the list.
*
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
//移除指定索引的元素。先通过索引找到节点,再移除指定的节点
public E remove(int index) {.
//检查是否越界
checkElementIndex(index);
//先找到节点,再移除指定节点
return unlink(node(index));
}
/**
* Returns the (non-null) Node at the specified element index.
*/
//如果索引位置在后面一半,就从后往前遍历查找,否则从前往后遍历。
Node<E> node(int index) {
// assert isElementIndex(index);
// size>>1 表示除以2,相当于index小于size的一半
if (index < (size >> 1)) {
// 从前面开始遍历,取出first节点,因为中间过程引用会变化,所以不可直接操作first
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;
}
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
更新操作
/**
* Replaces the element at the specified position in this list with the
* specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
//更新指定索引的位置的元素,返回旧值的元素
public E set(int index, E element) {
//检查索引是否越界
checkElementIndex(index);
//找到对应的节点
Node<E> x = node(index);
//记录旧值
E oldVal = x.item;
//修改元素
x.item = element;
return oldVal;
}
/**
* Returns the (non-null) Node at the specified element index.
*/
//如果索引位置在后面一半,就从后往前遍历查找,否则从前往后遍历。
Node<E> node(int index) {
// assert isElementIndex(index);
// size>>1 表示除以2,相当于index小于size的一半
if (index < (size >> 1)) {
// 从前面开始遍历,取出first节点,因为中间过程引用会变化,所以不可直接操作first
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;
}
}
queue相关的方法
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
//获取第一个元素
public E peek() {
// 拿到第一个元素,final不可变
final Node<E> f = first;.
//三目运算,获取item的值
return (f == null) ? null : f.item;
}
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
//获取队列第一个元素
public E element() {
return getFirst();
}
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
//移除队列第一个节点元素并返回
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
//移除队列第一个元素,
public E remove() {
return removeFirst();
}
/**
* Adds the specified element as the tail (last element) of this list.
*
* @param e the element to add
* @return {@code true} (as specified by {@link Queue#offer})
* @since 1.5
*/
//在队列后面添加元素
public boolean offer(E e) {
return add(e);
}
// Deque operations
/**
* Inserts the specified element at the front of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerFirst})
* @since 1.6
*/
//在队列前面插入元素
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
/**
* Inserts the specified element at the end of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerLast})
* @since 1.6
*/
//在队列最后插入元素
public boolean offerLast(E e) {
addLast(e);
return true;
}
/**
* Retrieves, but does not remove, the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
//获取第一个节点里面的元素
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* Retrieves, but does not remove, the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
//获取最后一个节点的元素
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
/**
* Retrieves and removes the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
//获取第一个元素,并移除
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* Retrieves and removes the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
//获取队列最后一个元素,并且移除它
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
//像是堆栈的特点,在前面添加元素
public void push(E e) {
addFirst(e);
}
/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this list (which is the top
* of the stack represented by this list)
* @throws NoSuchElementException if this list is empty
* @since 1.6
*/
//堆栈的特点,取出队列首的第一个元素
public E pop() {
return removeFirst();
}
final Node l = last;
return (l == null) ? null : unlinkLast(l);
}
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
//像是堆栈的特点,在前面添加元素
public void push(E e) {
addFirst(e);
}
/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this list (which is the top
* of the stack represented by this list)
* @throws NoSuchElementException if this list is empty
* @since 1.6
*/
//堆栈的特点,取出队列首的第一个元素
public E pop() {
return removeFirst();
}