概述
LinkedList
是用链表结构存储数据的,很适合数据的动态插入和删除,随机访问和遍历速度比较慢,另外它还提供了List
接口中没有定义的方法,专门用于操作表头和表尾元素,可当做堆栈,队列和双向队列使用。
链表的介绍
1.单向链表
单向链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始;链表是使用指针进行构造的列表;又称为结点列表,因为链表是由一个个结点组装起来的;其中每个结点都有指针成员变量指向列表中的下一个结点。链表是由结点构成,head指针指向第一个成为表头结点,而终止于最后一个指向NULL的指针。
2.单向循环链表
在单向链表的最后一个节点的next会指向头节点,而不是指向null,这样存成一个环。
3.双向链表
每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点
4.双向循环链表
第一个节点的pre指向最后一个节点,最后一个节点的next指向第一个节点,也形成一个“环”,构成双向循环链表
LinkedList的源码解析
1.UML图
- AbstractSequentialList 继承自AbstractList,但AbstractSequentialList 只支持按次序访问,而不像 AbstractList 那样支持随机访问。这是LinkedList随机访问效率低的原因之一。
- Deque:Deque,Double ended queue,双端队列。LinkedList可用作队列或双端队列就是因为实现了它。
- Cloneable,Serializable 拷贝和序列化
2.类的属性和核心数据结构
// List数据大小
transient int size = 0;
// 头结点
transient Node<E> first;
// 尾结点
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;
}
3.LinkedList#addFirst(E e) 添加到头结点
/**
* 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) {
// 设置f为头结点
final Node<E> f = first;
// 新节点
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
// f==null表示链表数据为空,当前元素e为第一个添加的元素
if (f == null)
last = newNode;
else
// 将新元素添加到头结点之上
f.prev = newNode;
size++;
modCount++;
}
/**
* 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++;
}
4.LinkedList#addLast(E e) 添加到尾结点
/**
* 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.
*/
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;
// 元素个数+1
size++;
// 修改次数+1
modCount++;
}
5.LinkedList#add(E e) 添加元素
/**
* 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;
}
6.LinkedList#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);
}
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; //建立前节点,后节点
//index==size,说明是在当前集合的末尾插入新数据,因此没有后节点,succ=null,前节点为当前集合的最后一个节点pred=last
if (index == size) {
succ = null;
pred = last;
} else { //找到当前下标指代的节点,要在该节点前插入数据,因此令succ等于该节点。
succ = node(index);
//pred则等于succ前面一位的节点。需要注意当index=0时,该节点可以为null。
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<>0,因此新的节点,作为前节点的后节点(pred.next)
pred.next = newNode;
// 令当前节点作为前节点,获取下一个元素,循环。
pred = newNode;
}
// succ == null说明是从当前集合的末尾开始插入数据,因此c集合中数据的最后一个元素循环完成最后一个pred,作为当前集合的last
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
// 元素个数计算
size += numNew;
// 更改次数++
modCount++;
return true;
}
// 检查要插入元素的开始的索引位置是否为从最后一个节点开始的
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;
}
从代码分析LinkedList添加元素不存在扩容或者数组的copy操作,所以相对于ArrayList,LinkedList更适合添加或者删除元素,只需要改变相关元素的指向即可。
7.LinkedList#add(int index, E element) 指定位置添加元素
/**
* 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) {
// 检查index时候越界
checkPositionIndex(index);
// index==size 表示添加在最后一个之后
if (index == size)
// 直接添加到最后一个元素
linkLast(element);
else
// 计算index位置的节点,并将添加的element添加到链表中
linkBefore(element, node(index));
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
// succ 中间变量-index位置下的节点。pred为succ的上边一个节点
final Node<E> pred = succ.prev;
// 构造新节点--pre为succ的上个节点,nex为succ节点
final Node<E> newNode = new Node<>(pred, e, succ);
// 设置succ的上个节点为最新构造的节点
succ.prev = newNode;
// 如果 pred为空表示succ为头结点
if (pred == null)
// 设置为当前节点为头结点
first = newNode;
else
// 否则 pred即succ的上个节点指向的下个节点为当前最新节点
pred.next = newNode;
size++;
modCount++;
}
上述linkBefore主要还是完成下图所表示的动作。
8.LinkedList#get(int index)
/**
* 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);
// linkedList是双向队列,此处判读index处于size的一半大小的上半部分还是下半部分-最大只需要遍历LinkedList最大长度的一版
if (index < (size >> 1)) { // index小于size/2
Node<E> x = first; // 从头结点开始遍历查找
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else { // index大于size/2
Node<E> x = last; //从尾结点开始遍历
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
从源码角度分许,LinkedList获取指定索引位置的元素,需要从头或者从尾部开始遍历查找索引位置的元素,最大遍历次数为LinkedList的size/2。
9.LinkedList#remove(int index)
/**
* 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) {
// 检查index索引是否越界
checkElementIndex(index);
// 断开index处的node链接
return unlink(node(index));
}
/**
* Unlinks non-null node x.
*/
E unlink(Node<E> x) {
// assert x != null;
// 获取但当节点的元素值
final E element = x.item;
// x元素的下个node节点
final Node<E> next = x.next;
// x的上个node节点
final Node<E> prev = x.prev;
// prev 为空表示x为第一个元素
if (prev == null) {
// 直接将next的node放在first位置
first = next;
} else {
// 否则将prev的next指向next
prev.next = next;
// 释放x的连接
x.prev = null;
}
// 如果next为空表示x为最后一个节点
if (next == null) {
// 将prev直接放在最后的节点位置
last = prev;
} else {
// 否则next的上个节点指向prev
next.prev = prev;
// x释放next的连接
x.next = null;
}
// 是指x.item为空,垃圾回收元素
x.item = null;
// 大小减1
size--;
// 修改次数+1
modCount++;
// 返回移除的元素
return element;
}
删除节点示意图
9.LinkedList#clear()
/**
* 将链表中的所有对象引用关系全部置为空,游离元素gc回收
* 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;
}
first = last = null;
size = 0;
modCount++;
}
以上我们就LinkedList
的核心方法和代码进行了分析。其他方法相对比较简单,要想具体了解其实现可以自行查看源码。