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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值