ArrayList 和linkedList区别联系
LinkedList与ArrayList一样实现List接口~~~~~~~~,只是ArrayList是List接口的大小可变数组的实现,LinkedList是List接口双向链表的实现。基于链表实现的方式使得LinkedList在插入和删除时更优于ArrayList,而随机访问则比ArrayList逊色些。
LinkedList实现所有可选的列表操作,并允许所有的元素包括null。
除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get、remove 和 insert 元素提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列或双端队列。
此类还实现 Deque 接口,为 add、poll 提供先进先出队列操作,以及其他堆栈和双端队列操作。
所有操作都是按照双重链接列表的需要执行的。在列表中编索引的操作将从开头或结尾遍历列表(从靠近指定索引的一端)。
同时,与ArrayList一样此实现不是同步的。
以上摘自JDK 6.0 API)。
定义
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
属性
private transient Entry header = new Entry(null, null, null);
private transient int size = 0;
private static class Entry<E> {
E element; //元素节点
Entry<E> next; //下一个元素
Entry<E> previous; //上一个元素
Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
添加
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);//新节点的上个节点为l,下节点为空
last = newNode;
if (l == null)
first = newNode;
else
//如果之前有的话,就是上次节点的下一个节点。
l.next = newNode;
size++;
modCount++;
}
删除
public E remove(int index) {
checkElementIndex(index);
//node(index)索引对应的节点,根据index更加考级头结点还是尾节点,然后从那个反向哪里找。
return unlink(node(index));
}
//查找对应索引
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Unlinks non-null node 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;
//判断删除的是否是头结点和尾节点。
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}