黑马程序员技术交流社区
标题:
ArrayList特有迭代器ListIterator的一点小细节
[打印本页]
作者:
谭立文
时间:
2012-10-7 22:16
标题:
ArrayList特有迭代器ListIterator的一点小细节
偶然碰到的,不知道大家碰到过没,分享一下。
package com.wenfengkeji.collection;
import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<Person> al = new ArrayList<Person>();
al.add(new Person("a", 18));
al.add(new Person("b", 16));
al.add(new Person("c", 20));
al.add(new Person("d", 21));
ListIterator<Person> lt = al.listIterator();
while(lt.hasNext())
{
Person p = lt.next();
if(p.getName().equals("a"))
{
//al.add(new Person("ok", 21)); //出错
System.out.println(al.size());
lt
.remove();
//若remove在add之后抛IllegalStateException
lt
.add(new Person("ok", 21));
/*
* lt.remove();
* 从列表中移除由 next 或 previous 返回的最后一个元素(可选操作)。
* 对于每个 next 或 previous 调用,只能执行一次此调用。只有在最后一次调用 next
* 或 previous 之后,尚未调用 ListIterator.add 时才可以执行该调用。
*/
System.out.println(al.size());
}
}
System.out.println(al);
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2