LinkedList整体架构
LinkedList底层是基于双向链表实现的,链表的每一个节点叫做Node,Node有一个属性prev,代表Node的前一个节点的位置,属性next代表Node后一个节点的位置。first是双向链表的头结点,其prev属性指向位置的为NULL。last是双向链表的尾结点,其next属性的指向NULL。当linkedList数据为空时,first节点和last节点是统一节点,该节点的prev和next都为null。因为LinkedList是基于双向链表实现的,只要机器的大小足够,理论上LinkedList是没有大小限制。其如整体架构的示意图如下:
其Node的源码如下:
private static class Node<E> {
// 节点的值
E item;
// Node的后一个节点
Node<E> next;
// Node的前一个节点
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
LinkedList类注解
- 双向链表实现了List和Deque的接口,实现所有可选列表操作,并允许所有,包括null.
- 所有操作均执行双链接所预期的操作清单。索引到链接中的操作将遍历链接开头或结尾,以更接近指定索引的位置为准。
- LinkedList是线程不安全的,如果需要线程安全可以使用Collections.synchronizedCollection()以防止意外
对列表的非同步访问。 - 如果LinkedList在遍历的时候数据被修改则会快速失败,抛出ConcurrentModificationException异常。
LinkedList主要的成员变量
// LinkedList实际的数据量的大小
transient int size = 0;
/**
* 双向链表的链表头结点
*/
transient Node<E> first;
/**
* 双向链表的链表尾结点
*/
transient Node<E> last;
LinkedList初始化
- 空的构造方法初始化。
public LinkedList() {
}
- 带初始数据的初始化,调用空构造方法,然后再调用addAll()方法,将数据进行添加。
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
LinkedList新增方法(从头部新增和从尾部新增)
从双线链表头节点新增,源码如下:
public boolean add(E e) {
linkLast(e);
return true;
}
// 从双向链表头结点开心添加
private void linkFirst(E e) {
// 将头结点的数据用临时节点f存储起来。
final Node<E> f = first;
// 新建一个Node节点,其prev值为null.
final Node<E> newNode = new Node<>(null, e, f);
// 将新建的节点赋给头结点
first = newNode;
// 头节点为空,就是链表为空,头尾节点是一个节点。
if (f == null)
// 此时头结点和尾结点都是同一个节点
last = newNode;
else
// 上一个头节点的前一个节点指向当前节点
f.prev = newNode;
// 大小和版本更改
size++;
modCount++;
}
从双线链表尾节点新增,源码如下:
void linkLast(E e) {
// 将双向链表的尾节点用一个临时节点l存放
final Node<E> l = last;
// 新建一个用于双向链表的节点用于做后面的节点
final Node<E> newNode = new Node<>(l, e, null);
// 将新的node节点重新赋值到尾结点
last = newNode;
// 如果链表为空(l 是尾节点,尾节点为空,链表即空),头部和尾部是同一个节点,都是新建的节点
if (l == null)
first = newNode;
// 否则把前尾节点的下一个节点,指向当前尾节点。
else
l.next = newNode;
// 大小和版本的修改。
size++;
modCount++;
}
头部追加节点和尾部追加节点非常类似,只是前者是移动头节点的 prev 指向,后者是移动尾节点的 next 指向。
LinkedList删除
从头结点删除:
// 删除当前头结点
public E removeFirst() {
final Node<E> f = first;
// 如果双向链表为空,则抛出异常。
if (f == null)
throw new NoSuchElementException();
// 否则调用unlinkFirst()删除头结点
return unlinkFirst(f);
}
private E unlinkFirst(Node<E> f) {
// 获取头结点的值存为临时变量,删除成功后的返回。
final E element = f.item;
// 获取头结点的下一个节点
final Node<E> next = f.next;
// 将头结点的值为null和将下一个断开关联。为了方便GC 回收。
f.item = null;
f.next = null;
// 将头节点重新赋值
first = next;
// 如果为空,则代表双向链表为空
if (next == null)
last = null;
else
// 断开头结点的联系
next.prev = null;
size--;
modCount++;
return element;
}
从尾结点删除也是如此:
头部删除节点和尾部删除节点非常类似,要么是prev断开或者next断开.
LinkedList获取元素
获取头结点的元素:
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;
}
获取双向链表中的元素(根据索引):
Node<E> node(int index) {
// 如果 index 处于队列的前半部分,从头开始找,size >> 1 是 size 除以 2 的意思。
if (index < (size >> 1)) {
Node<E> x = first;
// 直到 for 循环到 index 的前一个 node 停止
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
// 如果 index 处于队列的后半部分,从尾开始找
Node<E> x = last;
// 直到 for 循环到 index 的后一个 node 停止
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
LinkedList 和Queue方法对比
LinkedList 实现了 Queue 接口,在新增、删除、查询等方面增加了很多新的方法,这些方法在平时特别容易混淆,在链表为空的情况下,返回值也不太一样:
LinkedList的迭代器
因为 LinkedList 要实现双向的迭代访问,所以我们使用 Iterator 接口肯定不行了,因为 Iterator 只支持从头到尾的访问。Java 新增了一个迭代接口,叫做:ListIterator,这个接口提供了向前和向后的迭代方法。
ListIteratoe源码如下:
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
void set(E e);
void add(E e);
LinkedList实现的ListIeratoe的遍历:
private class ListItr implements ListIterator<E> {
//上一次执行 next() 或者 previos() 方法时的节点位置
private Node<E> lastReturned;
// 下一个节点
private Node<E> next;
// 下一个节点的索引位置
private int nextIndex;
// 版本记录
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
Node<E> lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size) {
action.accept(next.item);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
LinkedList与ArrayList区别:
1、从底层数据结构开始说起,然后以某一个方法为突破口深入,比如:最大的不同是两者底层的数据结构不同,ArrayList 底层是数组,LinkedList 底层是双向链表,两者的数据结构不同也导致了操作的 API 实现有所差异,拿新增实现来说,ArrayList 会先计算并决定是否扩容,然后把新增的数据直接赋值到数组上,而 LinkedList 仅仅只需要改变插入节点和其前后节点的指向位置关系即可。
2、ArrayList 更适合于快速的查找匹配,不适合频繁新增删除,像工作中经常会对元素进行匹配查询的场景比较合适,LinkedList 更适合于经常新增和删除,对查询反而很少的场景。
3、ArrayList 允许 null 值新增,也允许 null 值删除。删除 null 值时,是从头开始,找到第一值是 null 的元素删除;LinkedList 新增删除时对 null 值没有特殊校验,是允许新增和删除的。
总结
LinkedList底层是基于链表实现的在大多数场景,LinkedList 新增或者删除数据性能优于ArraYList的,但是查询性能没有ArrayList,非常适合进行修改的列表,也适合于要求有顺序、并且会按照顺序进行迭代的场景。