ListIterator previous 名不符实

在用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();
        }

由此可见,previous只是把索引指向前一个item,返回的仍然是当前的item;而next是真的返回下一个item

你可能感兴趣的:(ListIterator previous 名不符实)