在上一篇中,我们看到了Iterator是如何实现的,在JDK中还有一个接口ListIterator,它也具有迭代器的功能,那么它与Iterator又有什么联系和区别呢?看看下面的源码分析就知道了。
Iterator是普通基础的迭代器,它主要有HasNext(),next(),remove()三个方法。Listiterator增加了Iterator的功能。它的接口定义如下:
// 继承Iterator,并做了扩展
public interface ListIterator<E> extends Iterator<E> {
// 是否到达最后了
boolean hasNext();
// 获取元素
E next();
// 是否有前驱
boolean hasPrevious();
// 获取前驱元素
E previous();
// 获取下一个游标
int nextIndex();
// 获取前驱游标
int previousIndex();
// 删除元素
void remove();
// 修改元素
void set(E e);
// 增加元素
void add(E e);
}
从定义上看,它比Itrator接口,作了一定的扩展,最明显的有两点:
1. Itrator只能从前到后的访问,而ListItrator可以向前访问;
2. Itrator在访问的过程中没有增加/修改元素的功能,而ListItrator有。
下面看看它是如何实现的吧。
// 继承Itr,并且实现ListIterator接口
private class ListItr extends Itr implements ListIterator<E> {
// 指定从哪个游标开始访问
ListItr(int index) {
super();
cursor = index;
}
// 是否到达首元素
public boolean hasPrevious() {
return cursor != 0;
}
// 返回下个元素的游标
public int nextIndex() {
return cursor;
}
// 返回上个元素的游标
public int previousIndex() {
return cursor - 1;
}
// 返回前驱元素
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
// 修改最近返回元素的值
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
// 在下一个元素位置添加元素
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}