集合系列中的LinkedList的源码解析
LinkedList内部实现
LinkedList内部定义的Node静态类
```java
private static class Node<E> {
E item;//数据
Node<E> next;//下一个Node节点,当前为链表尾时为null
Node<E> prev;//上一个Node节点,当前为链表头时为null
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
```
通过Node的定义可以知道,内部其实是一个双向链表,分别保存了前后两个节点的指向。
内部定义了两个成员变量first以及last,用于快速的获取当前数据的第一个和最后一个数据。
不管是实现list还是queue,直接操作first和last方法只有如下4个:
/**
* Links e as first element.
* 将元素添加到首位
*/
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
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++;
}
/**
* Unlinks non-null first node f.
* 将一个非空的节点从首位移除
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
/**
* 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
prev.next = null;
size--;
modCount++;
return element;
}
从上面的方法可以看到,操作first和last顶多就是修改一下指针的指向,效率很高。
关于位置的查找,最终调用的如下2个方法:
public int indexOf(Object o) {
int index = 0;
//元素分为null以及非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;
}
Node<E> node(int index) {
// assert isElementIndex(index);
//index在前一半则从前往后遍历,否则从后往前,减少几次遍历,提高一点效率
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;
}
}
List以及Dequeue的实现
list以及Deque的抽象实现,内部其实都是调用到linkFirst()、linkLast()、unLinkFirst()、unLinkLast()不再赘述。
LinkedList特性
- 内部使用链表结构实现,特点是增、删快,查询慢(需要从头遍历)
- 实现了Deque接口,也可以当作Queue来使用