*本文只是备忘录。
JAVA中List的实现主要有ArrayList、vector、stack、LinkedList,以及一个抽象的类AbstractList.
1、LinkedLIst
LinkedList 被称作双向链表。索引速度慢,插入、删除速度快。
为什么被成为双向链表,应为当前对象拥有了该对象之前的对象的引用和该对象之后的引用。
不同于ArrayList通过数组保存对象,LinkedList通过一个内部数据结构Node<E>来保存对象。
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;
}
}
我们可以看到 该数据结构中保存了3个对象,一个是当前的对象 Item,一个上一个对象的引用prev,一个后一个对象的引用next。
每次插入元素的时候只需要保存前后元素即可。但是如果索引就需要遍历整个linkedLis(当然其实是一半)。
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
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;
/**
* Constructs an empty list.
*/
public LinkedList() {
}
LinkedList保存了对象个数,第一个和最后一个对象。方便用来计算。
来看看add方法:
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* 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++;
}
add方法在末尾添加一个对象,只需要将原来的末尾对象oldLast取出,然后将oldLast的next指向新加入的对象。同时将该对象的prev指向oldLast即可。当然新加如的对象就是最后位置的对象(当然需要创建一个Node结构),需要赋值给last(上面说的LinkedList保存的最后对象)。
另外一个在指定位置加入对象的方法:
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
通过linkBefore来插入对象,linkBefore()方法2个参数,一个是插入的对象,一个是插入对象原先位置的node信息。
关键的方法是node(index)方法,查找指定位置的Node对象的方法。来看看如何实现:
Node<E> node(int index) {
// assert isElementIndex(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;
}
}
可以看到是遍历获取指定位置的Node。根据传入的index的值判断是冲前获取,还是冲后获取,减少循环次数。
涉及到linkedList的索引操作都需要遍历整个list,所以会比较慢。