Iterator与LinkedIterator
Iterator与LinkedIterator分别是两个接口,LinkedIterator继承自Iterator接口,所以LinkedIterator会比Iterator多一些方法
Iterator的方法:
boolean hasNext();
E next();
void remove();
ListIterator的方法:
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
void set(E e);
void add(E e);
ListIterator是支持双向遍历的,Iterator只支持单向遍历。
ArrayList、LinkedList对二者的实现
先看一下ArrayList与LinkedList实现的位置关系图,以及各自的实现方式
ArrayList的实现
ArrayList首先是实现了Iterator接口,实现类为Itr
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
}
定义了cursor与LastRet,以及fail-fast 机制的 expectedModCount。上图中四自己关于cursor与元素相对位置理解图,可以方便想象相对位置,以免混乱。
接下来ArrayList实现了ListIterator接口,实现类是ListItr,继承了Itr,然后对相关方法进行了实现。
private class ListItr extends Itr implements ListIterator<E>{
ListItr(int index) {
super();
cursor = index;
}
}
ArrayList中iterator()方法返回的是Itr对象
public Iterator<E> iterator() {
return new Itr();
}
ArrayList中Listiterator方法进行了重载,有两种调用ListItr的方法
//默认开始位置为0
public ListIterator<E> listIterator() {
return new ListItr(0);
}
//自定义cursor初始位置
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
LinkedList实现
LinkedList实现了ListIterator接口,实现类为ListItr
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
}
定义了 private Node<E> lastReturned;记录上一次遍历的位置,主要用于set与remove方法之前
private Node<E> next;记录下一个节点
private int nextIndex;记录下一节点的Index
private int expectedModCount = modCount;fail-fast 机制的 expectedModCount
接下来就对ListIterator的各种方法进行了实现。
LinkedList中listIterator(int index)方法返回的是ListItr对象
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
LinkedList中还有一个DescendingIterator实现了Iterator接口,反向遍历,还是借助ListItr实现的
private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}
总结
Iterator与LinkedIterator分别是两个接口,LinkedIterator继承自Iterator接口,所以LinkedIterator会比Iterator多一些方法,LinkedIterator中有反向遍历,对队列,链表使用更方便吧。
ArrayList与LinkedList都实现了这些接口,不过LinkedList中实现Iterator接口是反向遍历。具体还是看图吧哈哈哈哈哈