-
实现接口
看上图,LinkedList
和ArrayList
稍微有不一样的东西,那就是RandomAccess
和Deque
,实现了双端队列,ArrayList
实现RandomAccess
遍历,快速访问,接口中说理论for优于Iterator迭代。所以快速访问,查找ArrayList
优于LinkedList
,but增删反之。查找迭代,说实际的还不好确定,按文档来说是优于LinkedList
的。
Deque继承Queue,api如下,主要针对如队列出队列操作。
不同颜色操作不一样,详情后面文章会进行介绍。
- 内部实现原理
内部使用Node<E>
对象实现,数据保存first和last对象:
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;
}
}
就是使用prev和next保存数据的之间的关系,内存不需要连续。学过数据结构的应该会熟悉。
-
Iterator实现
Iterator()方法返回listIterator实现。取得具体的遍历对象使用下列方法:
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned = null;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index); // 这儿是调用上图中遍历取得的对象。使用next,prev迭代。
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
Node<E> lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
好了,基本完成了。