
Iterator接口是对collection进行迭代的迭代器,ListIterator接口是其子接口。它们都是遍历集合的工具。
Collection依赖于Iterator,其实现类都必须实现iterator()函数,返回一个Iterator对象;ListIterator是专门遍历List而存在的。
Iterator
Iterator迭代器包含以下三种方法:
boolean hasNext():如果仍有元素可以迭代,则返回 trueE next():返回迭代的下一个元素void remove():从迭代器指向的 collection 中移除迭代器返回的最后一个元素,每次调用 next 只能调用一次此方法
ListIterator
ListIterator迭代器包含以下九种方法:
void add(E e):将指定的元素插入列表boolean hasNext():以正向遍历列表时,如果列表迭代器有多个元素,则返回 trueboolean hasPrevious():如果以逆向遍历列表,列表迭代器有多个元素,则返回 trueE next():返回列表中的下一个元素int nextIndex():返回对 next 的后续调用所返回元素的索引E previous():返回列表中的前一个元素int previousIndex():返回对 previous 的后续调用所返回元素的索引void remove():从列表中移除由 next 或 previous 返回的最后一个元素void set(E e):用指定元素替换 next 或 previous 返回的最后一个元素
比较
相同点:都可以对集合中的元素进行遍历
不同点:
- 使用范围不同,
Iterator可应用于所有的集合,而ListIterator只能用于List及其子类型,如List、ArrayList、LinkedList和Vector等 ListIterator可通过set()方法实现对象的修改,而Iterator不能ListIterator可通过nextIndex()或previousIndex()得到后续调用所返回元素的索引,而Iterator不能ListIterator可实现双向遍历,而Iterator只能顺序向前遍历ListIterator可通过add()添加对象,而Iterator不能
要特别注意的是:长度为n的列表的迭代器有n+1种可能的指针位置,指针位置总是两个位于元素之间

Demo
/**
* @author GongchuangSu
* @since 2016.05.10
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class IteratorDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
System.out.print("Original contents of al: ");
Iterator<String> it = al.iterator();
while(it.hasNext()){
System.out.print(it.next() + " ");
}
System.out.println();
ListIterator<String> lt = al.listIterator();
while(lt.hasNext()){
lt.set(lt.next() + "+");
}
System.out.print("Modified contents of al: ");
lt = al.listIterator();
while(lt.hasNext()){
System.out.print(lt.nextIndex() + ":");
System.out.print(lt.next() + " ");
}
System.out.println();
System.out.print("Modified list backwards: ");
while(lt.hasPrevious()){
System.out.print(lt.previousIndex() + ":");
System.out.print(lt.previous() + " ");
}
}
}
本文详细介绍了Iterator和ListIterator接口的功能及使用方法,对比了两者之间的异同,并通过示例代码展示了如何利用这两种迭代器来遍历集合。

1309

被折叠的 条评论
为什么被折叠?



