在用ListIterator previous时遇到一个问题,参见下面示例代码:
ListIterator< HistoryItem> iterators = curStack.listIterator();
while ( iterators.hasNext() ) {
HistoryItem item = iterators.next();
if ( item.getActivity() == activity ) {
item = iterators.previous();
......
break;
}
}
在调用ListIterator::next后,希望调用previous返回上一个item,但是不正确,返回的还是当前的item.
分析下源码是这样的:
public E previous() {
if (expectedModCount == modCount) {
try {
E result = get(pos); // pos是当前位置,返回当前item,并且pos-1
lastPosition = pos;
pos--;
return result;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
throw new ConcurrentModificationException();
}
public E next() {
if (expectedModCount == modCount) {
try {
E result = get(pos + 1); // 返回当前下一个item,并且pos+1
lastPosition = ++pos;
return result;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
throw new ConcurrentModificationException();
}