java迭代器筛选list,java集合之迭代器ListIterator

首先,我们来看一段程序:

public static void main(String[] args)

{

ArrayList list = new ArrayList();

list.add(1);

list.add(2);

list.add(3);

list.add(4);

for(ListIterator iter = list.listIterator();iter.hasNext();)

{

System.out.println(iter.next());

System.out.println(iter.next());

System.out.println(iter.next());

System.out.println(iter.previous());

System.out.println(iter.next());

System.out.println(iter.next());

break;

}

}

你能写出它的结果吗?

结果是1,2,3,3,3,4.

是不是很奇怪?你心中的结果是不是1,2,3,2,3,4.

其实我们可以看看next()和previous的相关java源码:

private class Itr implements Iterator {

/**

* Index of element to be returned by subsequent call to next.

*/

int cursor = 0;

/**

* Index of element returned by most recent call to next or

* previous. Reset to -1 if this element is deleted by a call

* to remove.

*/

int lastRet = -1;

根据解释,cursor表示下一个待访问的位置,lastRet表示最近访问过的位置。

public E next() {

checkForComodification();

try {

E next = get(cursor);

lastRet = cursor++;

return next;

} catch (IndexOutOfBoundsException e) {

checkForComodification();

throw new NoSuchElementException();

}

}

在调用next方法时,先得到cursor处的值,然后lastRet=cursor,返回cursor处的值。也就是说在返回当前值得时候,cursor已经走到下一个位置了。

public E previous() {

checkForComodification();

try {

int i = cursor - 1;

E previous = get(i);

lastRet = cursor = i;

return previous;

} catch (IndexOutOfBoundsException e) {

checkForComodification();

throw new NoSuchElementException();

}

}

在调用previous方法时,先将cursor-1赋值给i,然后得到i处的值,继而将i给cursor及lastRet,最后返回i处的值。也就是说在调用previous时,先将cursor-1,然后将lastRet赋值cursor-1,再返回cursor处的值。和next()不同的是,next是先取值再加1,previous()是先减1,再取值。 看到这里,我们就不难得出结果了,自己动手画画吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值