java Iterator的next()、previous()、set()究竟指向哪里?

初学时被搞迷糊了,看了源码才知道是什么意思。

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
回退时同理。

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值