LinkedList底层分析
源码场景
java
LinkedList<String> list = new LinkedList<>();
list.add("小宇");
list.add("小蒲");
list.add("小康");
源码分析
java
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
//外部操作数
protected transient int modCount = 0;
}
java
public abstract class AbstractSequentialList<E> extends AbstractList<E> {
}
java
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>{
//元素个数
transient int size = 0;//0
//第一个节点
transient Node<E> first;//null
//最后一个节点
transient Node<E> last;//null
public LinkedList() {
}
public boolean add(E e) {
linkLast(e);
return true;
}
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++;
}
//节点类
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;
}
}
}