首先,我们来看一段程序:
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
for(ListIterator<Integer> iter = list.listIterator();iter.hasNext();)
{
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.next());
System.out.println(iter.previous());
System.out.println(iter.next());
System.out.println(iter.next());
break;
}
}
你能写出它的结果吗?
结果是1,2,3,3,3,4.
是不是很奇怪?你心中的结果是不是1,2,3,2,3,4.
其实我们可以看看next()和previous的相关java源码:
private class Itr implements Iterator<E> {
/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
根据解释,cursor表示下一个待访问的位置,lastRet表示最近访问过的位置。
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
在调用next方法时,先得到cursor处的值,然后lastRet=cursor,返回cursor处的值。也就是说在返回当前值得时候,cursor已经走到下一个位置了。
public E previous() {
checkForComodification();
try {
int i = cursor - 1;
E previous = get(i);
lastRet = cursor = i;
return previous;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
在调用previous方法时,先将cursor-1赋值给i,然后得到i处的值,继而将i给cursor及lastRet,最后返回i处的值。也就是说在调用previous时,先将cursor-1,然后将lastRet赋值cursor-1,再返回cursor处的值。和next()不同的是,next是先取值再加1,previous()是先减1,再取值。看到这里,我们就不难得出结果了,自己动手画画吧!