集合的ListIterator的用法

来源:互联网 发布:linux改文件名 编辑:程序博客网 时间:2024/06/11 13:37
  在说ListIterator之前,对于Iterator迭代器都应该很熟悉,在jdk1.2后出现的,代替了Enumeration接口,用于集合的遍历操作。而ListIterator也是迭代器,它的父接口就是Iterator,主要用于List及其子类型。
  public interface ListIterator<E> extends Iterator<E>
查看源码:
public interface ListIterator<E> extends Iterator<E> {    //正向遍历列表时,如果列表迭代器有多个元素,则返回 true    boolean hasNext();    //返回列表中的下一个元素    E next();    //返回对next的后续调用所返回元素的索引    int nextIndex();    //如果以逆向遍历列表,列表迭代器有多个元素,则返回 true    boolean hasPrevious();    //返回列表中的前一个元素    E previous();    //返回对previous的后续调用所返回元素的索引    int previousIndex();    //从列表中移除由next或previous返回的最后一个元素    void remove();    //用指定元素替换next或previous返回的最后一个元素    void set(E e);    //将指定的元素插入列表    void add(E e);}
用法示例
public class ListIteratorTest {@Testpublic void test1(){List<String> list = new ArrayList<String>();list.add("one");list.add("two");list.add("three");list.add("four");ListIterator<String> iter = list.listIterator();//正向遍历while(iter.hasNext()){//获取元素的索引int index = iter.nextIndex();String str = iter.next();System.out.println(index+":"+str);}System.out.println("---------------------------");//反向遍历while(iter.hasPrevious()){//获取元素的索引int index = iter.previousIndex();String str = iter.previous();System.out.println(index+":"+str);}}@Testpublic void test2(){List<String> list = new ArrayList<String>();list.add("one");list.add("two");list.add("three");list.add("four");ListIterator<String> iter = list.listIterator();iter.next();System.out.println(list);//[one, two, three, four]//指定元素替换next()返回的值iter.set("AA");System.out.println(list);//[AA, two, three, four]//删除元素"AA"iter.remove();System.out.println(list);//[two, three, four]//添加元素iter.add("BB");System.out.println(list);//[BB, two, three, four]}}
总结:Iterator和ListIterator区别和联系?相同点:都是迭代器,当需要对集合中的元素进行遍历而不需要干预遍历过程时,两种都可以使用不同点:1).使用范围不同,Iterator可以应用于所有集合,Set,List和Map和这些集合的子类型,而ListIterator只能用于List及其子类型2).ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历,但是ListIterator有hasPrevious()和 previous()方法实现逆向(顺序向前遍历)3).ListIterator可以定位当前索引的位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能4).ListIterator有add方法,可以向List中添加对象,而Iterator不能5).都可以实现删除对象,但是ListIterator可以实现对象的修改,Iterator只能遍历不能修改