LinkedList源码剖析
LinkedList实现了List, Deque接口,可以当做List 或者双端队列使用,内部使用链表实现,所以没有扩容,也没有容量限制
主要成员属性
// 元素个数
transient int size = 0;
/**
* Pointer to first node.
*/
// 存放第一个节点元素 头指针
transient Node<E> first;
/**
* Pointer to last node.
*/
// 存放最后一个节点元素 尾指针
transient Node<E> last;
Node
成员属性 采用双指针实现双端队列, 遍历寻找元素时根据位置决定使用正向遍历还是逆向遍历
// 存储数据
E item;
// 后置指针
Node<E> next;
// 前置指针
Node<E> prev;
主要方法
构造方法
LinkedList并没有容量的概念,自然也没有初始化容量的构造方法
/**
* 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();
// 将集合 c 中的所有元素添加进去
addAll(c);
}
linkFirst
在头部插入都是使用的这个方法,具体实现下面看下源码:
/**
* Links e as first element.
* 将 e 作为第一个节点
*/
private void linkFirst(E e) {
final Node<E> f = first;
// 构建节点 要作为第一个节点所以 prev 为 null 数据为 item 将当前的头节点连接至新节点
final Node<E> newNode = new Node<>(null, e, f);
// 将构建出来的新节点赋值给头节点
first = newNode;
// 如果 原来的头节点为 null 说明之前没有元素 当前只有一个元素, 即尾节点也是当前节点
if (f == null)
last = newNode;
// 否则将之前的头节点的 prev 指针指向构建出来的新节点
else
f.prev = newNode;
// 元素个数 + 1
size++;
// 修改次数 + 1
modCount++;
}
linkLast
在尾部追加都是使用的这个方法,下面也来看下源码实现
/**
* Links e as last element.
* 将 e 作为最后一个节点
*/
void linkLast(E e) {
final Node<E> l = last;
// 构建节点 要作为最后一个节点 所以 next 指针为 null ,prev 指针为当前尾节点
final Node<E> newNode = new Node<>(l, e, null);
// 将构建出来的新节点赋值给尾节点
last = newNode;
// 如果之前的尾节点为 null 说明之前没有元素 当前只有一个元素 即头节点也是当前构建出来的节点
if (l == null)
first = newNode;
else
// 否则 将尾节点的 next 指向构建出来的新节点
l.next = newNode;
// 元素个数 + 1
size++;
// 修改次数 + 1
modCount++;
}
linkBefore
将节点 插入到到 succ 节点之前 ,指定位置插入均使用的这个方法
/**
* Inserts element e before non-null Node succ.
* 将节点 e 连接到 succ 节点之前
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
// 构建新节点 prev 指针为 succ 的prev 指针 next 指针为 succ
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
// 将 succ 的 prev 指针指向到新构建出来的节点
succ.prev = newNode;
// 上面已经插入完成
// 如果 succ 的 prev 指针为 null 说明 之前 succ 为头节点
if (pred == null)
// 将头节点赋值为新构建的节点
first = newNode;
else
// 否则不是头节点, 将 succ 插入前的前一个节点的 next 指针指向新构建的节点
pred.next = newNode;
// 元素个数 + 1
size++;
// 修改次数 + 1
modCount++;
}
unlinkFirst
删除头部元素均使用的这个方法
/**
* Unlinks non-null first node f.
* 解除头节点 f 链接
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
// 取出 node 节点的数据
final E element = f.item;
final Node<E> next = f.next;
// f 为头节点 prev 指针为 null item 以及 next 指针已经获取到 f 节点已经无用 将属性置为 null
// 在三色标记阶段 将 f 标记为黑色 若不设置为 null 还需要经历 灰色
f.item = null;
f.next = null; // help GC
// 将 f 的 next 指针赋值给头指针
first = next;
// 如果 next 指针为 null 说明当前仅有一个元素, 移除后为空 直接将尾节点置为 null
if (next == null)
last = null;
else
// 否则不是只有一个元素 将 next 的 prev 指针置为 null 因为此时 next 为头节点
next.prev = null;
// 元素个数 - 1
size--;
// 修改次数 + 1
modCount++;
return element;
}
unlinkLast
删除尾部元素均使用的这个方法
/**
* Unlinks non-null last node l.
* 解除尾节点 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
// 将 prev 赋值到 尾指针
last = prev;
// 如果 prev 为 null 说明仅有一个元素 头指针也置为 null
if (prev == null)
first = null;
else
// 否则将 prev 的 next 指针置为 null
prev.next = null;
// 元素个数 - 1
size--;
// 修改次数 + 1
modCount++;
return element;
}
unlink
删除指定位置的元素采用的这个方法
/**
* Unlinks non-null node x.
* 移除 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;
// 如果 prev 指针为 null 说明是头指针 将下一个节点赋值给头指针
if (prev == null) {
first = next; // 一
} else {
// 将 prev 节点的 next 指向 next
prev.next = next; // 二
x.prev = null;
}
// 如果 next 为 null 说明是尾指针 将上一个节点赋值给尾指针
if (next == null) {
last = prev; // 三
} else {
// 将 next 的prev 指向 prev
next.prev = prev; // 四
x.next = null;
}
// 共四种情况
// 1、是头指针也是尾指针 说明只有一个元素, 当前节点的 prev 和 next 指针都为null 会走 一、 三
// 将头尾指针都设置为null
// 2、是头指针不是尾指针说明有多个元素, 当前节点的prev 为null next不为null 走 一、 四
// 将头指针设置为当前节点的next 指针 并且断开当前节点的 next引用 并且处理头节点的prev指针
// 3、不是头指针是尾指针 将尾指针设置为当前节点的prev指针, 并断开当前节点的prev引用
// 4、既不是头指针也不是尾指针,将前一个节点的next指针指向下一个节点
// 将下一个节点的prev指针指向前一个节点
// 分别处理前置指针 prev 和后置指针 next
// 将数据置为 null
x.item = null;
// 元素数量 - 1
size--;
// 修改次数 + 1
modCount++;
// 返回断开链接的元素
return element;
}
getFirst
/**
* Returns the first element in this list.
* 返回第一个元素
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
getLast
/**
* Returns the last element in this list.
* 返回最后一个元素
* @return the last element in this list
* @throws NoSuchElementException if this list is empty */
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
removeFirst
移除第一个元素,可以看到其实还是调用的 unlinkFirst 方法
/**
* 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);
}
removeLast
移除最后一个元素,可以看到其实还是调用的 unlinkLast 方法
/**
* 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);
}
addFirst
在头部添加元素,可以看到其实还是调用的 linkFirst 方法
/**
* Inserts the specified element at the beginning of this list.
* 在链表头部添加元素
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
addLast
在尾部添加元素,可以看到其实还是调用的 linkLast 方法
/**
* 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);
}
contains
返回是否存在元素 内部调用的 indexOf 方法, 这个方法等下看
/** * Returns {@code true} if this list contains the specified element. * More formally, returns {@code true} if and only if this list contains * at least one element {@code e} such that * {@code Objects.equals(o, e)}. * * 返回集合是否存在元素 * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element */public boolean contains(Object o) { return indexOf(o) >= 0;}
size
/**
* Returns the number of elements in this list.
* 返回元素个数
* @return the number of elements in this list */
public int size() {
return size;
}
add
同样是调用的 linkLast 方法
/**
* 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;
}
/**
* 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).
* 将元素 element 插入到对应下标的位置
* @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
// 否则在对应下标位置的节点之前插入元素
linkBefore(element, node(index));
}
remove
移除元素,可以看出来先找到这个元素所在的节点,还是调用的unlink
/**
* 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
* {@code Objects.equals(o, get(i))}
* (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) {
// null 使用 ==
// 从头结点开始遍历 移除第一个元素
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
// 不是 null 使用 equals 比较
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
/**
* 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));
}
/**
* 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();
}
addAll
/**
* 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.)
*
* 将集合 c 中的所有元素添加到尾部
*
* @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.
*
* 将集合 c 添加到从 index 开始的位置
*
* @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) {
// 校验 index 合法性
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
// 空集合直接返回 false
if (numNew == 0)
return false;
// pred 为要添加位置的前一个元素
Node<E> pred, succ;
// 如果添加到尾部
if (index == size) {
succ = null;
pred = last;
} else {
// 获取对应位置的 Node 节点
succ = node(index);
pred = succ.prev;
}
// 遍历数组 a
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
// 构建节点
Node<E> newNode = new Node<>(pred, e, null);
// 当前 LinkedList 为空集合
if (pred == null)
// 将构建出来的节点赋值给头结点
first = newNode;
else
// 否则赋值给 pred 的 next 指针
pred.next = newNode;
// pred 后移
pred = newNode;
}
// 如果 succ 为 null 说明直接追加
if (succ == null) {
// 将添加的最后一个元素赋值给尾指针
last = pred;
} else {
// 添加到中间位置
// 将新增加的最后一个节点的 next 指向之前插入位置的后一个节点
pred.next = succ;
// 将插入位置的后一个节点的 prev 指向添加的最后一个节点
succ.prev = pred;
}
// 元素个数增加
size += numNew;
// 修改次数 + 1
modCount++;
return true;
}
clear
/**
* 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
// 遍历 将所有元素的各个属性置为 null
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;
// 元素个数置为0
size = 0;
// 修改次数 + 1
modCount++;
}
get
/**
* 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;
}
set
/**
* Replaces the element at the specified position in this list with the
* specified element.
* 将对应下标的元素设置为 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;
}
isElementIndex
/**
* Tells if the argument is the index of an existing element.
* 返回当前参数是否为集合的合法下标
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
node
这个方法返回对应位置的 Node 节点 中间插入以及中间删除均使用到了这个方法
/**
* Returns the (non-null) Node at the specified element index.
* 返回对应位置的 Node 节点
*/
Node<E> node(int index) {
// assert isElementIndex(index);
// 判断下标 index 是否大于 0.5 * size 小于从头指针遍历 大于从尾指针遍历
if (index < (size >> 1)) {
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;
}
}
indexOf
/**
* 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
* {@code Objects.equals(o, get(i))},
* 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 使用 == 否则使用 equals 比较
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;
}
lastIndexOf
/**
* 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
* {@code Objects.equals(o, get(i))},
* 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
*/
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;
}
peek
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* 返回第一个元素 不存在返回 null
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
element
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* 返回第一个元素 不存在抛出 NoSuhElementException 异常
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E element() {
return getFirst();
}
poll
弹出队首元素
/**
* 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);
}
offer
/**
* 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);
}
offerFirst
/**
* 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;
}
offerLast
/**
* 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);
}
push
/**
* 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);
}
pop
/**
* 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();
}
迭代器
先来看下迭代器的定义
private class ListItr implements ListIterator<E> {
// 最后一个返回的节点
private Node<E> lastReturned;
// 下一个要访问的元素
private Node<E> next;
// 下一个元素的下标
private int nextIndex;
// 修改次数 用来校验迭代过程中 LinkedList 是否发生过修改操作
private int expectedModCount = modCount;
}
构造方法
// 返回从下标 index 开始的迭代器
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
hasNext
public boolean hasNext() {
return nextIndex < size;
}
next
// 返回下一个元素 并且指针后移
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
// 指针后移
next = next.next;
nextIndex++;
return lastReturned.item;
}
set
// 修改当前元素
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
add
// 在当前位置插入元素
public void add(E e) {
checkForComodification();
lastReturned = null;
// 下一个访问的元素为 null 尾部追加
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
ArrayList 与 LinkedList区别
ArrayList
- ArrayList底层使用数据实现,有最大容量限制 为 int的最大值 - 8,并且可以指定初始化容量
- 当容量不足时会扩容 ,1.5倍扩容(向下取整),并且数组扩容需要复制,频繁扩容会导致频繁的数组复制,所以知道容量最好指定容量大小,并且数组可以随机访问,根据数组首地址 + 偏移量可以直接获取到对应位置的元素
优势
- 随机访问快
劣势
- 中间操作效率较低,涉及到数组的移动(移动使用数组复制的方式)
LinkedList
- LinkedList使用双向链表实现,没有最大容量限制,不可指定初始化容量大小
- 没有容量的概念,不会扩容,每次新增元素都新构建节点 ,因为使用链表,所以不可随机访问只能顺序访问,要访问特定位置的元素必须从头结点或者尾结点遍历
优势
- 没有容量大小限制,没有扩容所带来的复制
- 中间修改操作快捷,只需要改变修改元素前后元素的指向即可
劣势
- 不能随机访问,只能通过遍历查找,效率较低