这几天一直在看java源码,现在讲下LinkedList的数据结构
LinkedList和ArrayList都是线性结构的,细分的话ArrayList属于数组结构的
LinkedList属于链表结构的,我们先看下LinkedList中的Node私有内部类
private static class Node<E> {
E item; //当前元素
Node<E> next; //LinkedList中当前节点的下一个元素
Node<E> prev; //当前元素的上一个元素
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
这就决定了当前元素的next指向它的下一个元素,当前元素的prev指向它的上一个元素,LInkedList就是通过这种结构连接一个接着一个元素。
下一步我们再看下LinkedList中内部变量
protected transient int modCount = 0; //对集合操作的次数,这个变量所属于AbstractList类
transient int size = 0; //集合的长度
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first; //在集合中的第一个元素
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last; //在集合中的最后一个元素
新增的方法:
addFirst(E e); 新增到头 ,上面有我写的注释
private void linkFirst(E e) {
final Node<E> f = first;
//新的Node,next下一个节点为原来的首元素,prev上一个元素为null,e为当前元素
final Node<E> newNode = new Node<>(null, e, f);
first = newNode; //将第一个元素指向新增加的元素
if (f == null)
last = newNode; //如果原来的首元素为null,最后一个元素也是新增加的元素
else
f.prev = newNode;//如果不为null,原来元素的prev前一个元素为新增加的元素
size++; //集合长度加一
modCount++; //当前集合的操作次数加一
}
addLast(E e) ; 新增到结尾,代码里面有我写的流程注释
void linkLast(E e) {
final Node<E> l = last; //l指向原尾元素
//new一个新的节点元素,l为新元素的prev,e为当前的元素,当前元素的next为null
final Node<E> newNode = new Node<>(l, e, null);
last = newNode; //last指向新建节点
if (l == null)
first = newNode; //如果集合原来的长度为0,即尾元素为null,则首节点指向新增的节点
else
l.next = newNode; //否则原尾节点的next指向新增的节点
size++; //集合的长度自增一
modCount++; //集合的操作次数自增一
}
addFirst和addLast方法都是比较简单的,add(E e)内部调用了addLast的方法,将新增的元素插入集合的末尾
add(int index , E element) 这个方法是将指定的元素插入到集合指定的索引里面
public void add(int index, E element) {
//这个方法是对索引进行校验,如果index大于size或者index<0会抛出异常;
checkPositionIndex(index);
if (index == size)
linkLast(element);//如果插入的索引和集合的长度相同时,就直接插入集合的尾部
else
linkBefore(element, node(index)); //下面主要讲解下linkBefore和node这两个方法的作用
}
Node<E> node(int index) {
// assert isElementIndex(index);
//在这不得不为作者的编程思想鼓掌,如果插入的索引小于size/2,就从first开始遍历获取当前索引的节点,否则从last集合的尾部开始遍历获取索引所在的节点并返回,提高了近一倍的效率
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;
}
}
//参数 要插入集合的元素, succ,插入之前index所对应的节点元素
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev; //获取succ的上一个元素的引用,如果pred不为null,就让这个引用的next指向新增的节点元素,否则新增的元素为该集合的第一个元素节点
final Node<E> newNode = new Node<>(pred, e, succ); //新增的元素,succ作为他的下一个元素节点,pred作为他的上一个元素
succ.prev = newNode; //原来的succ的上一个元素指向新增的元素
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++; // 长度自增1
modCount++; //修改记录自增1
}
好啦,先把新增的几个方案了解了,就了解了linkedList的数据结构,以后的remove了的方法自己可以尝试下自己写一个试试啦