初学时被搞迷糊了,看了源码才知道是什么意思。
An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the carets (^) below:
Note that the remove and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last element returned by a call to next or previous().
iterator 不指向任何元素,它指向的是元素的间隔。
而set()所修改的元素,是其上一次调用next()或者previous()方法所返回的元素。
LinkedList<Integer> nums = new LinkedList<Integer>();
for(int i = 0; i < 5; ++i) nums.add(i);
ListIterator<Integer> itr = nums.listIterator();
for(;itr.hasNext();)
System.out.print(itr.next()+" ");//遍历1
itr.set(8848);
System.out.print("\n");
for(;itr.hasPrevious();)//遍历2
System.out.print(itr.previous()+" ");
System.out.print("\n");
for(;itr.hasNext();){//遍历3
System.out.print(itr.next()+" ");
}
输出结果:
0 1 2 3 4
8848 3 2 1 0
0 1 2 3 8848
上面的iterator与list的关系如图:
当iterator的cursor为1,它的next()返回1,previous返回0
第一次遍历,cursor: 0
→
\rightarrow
→ 1
→
\rightarrow
→ 2
→
\rightarrow
→ 3
→
\rightarrow
→ 4
→
\rightarrow
→ 5,最后一次next的返回值是4,因此set修改的是4
回退时同理。