0x00
Iterator:是一个接口,对 collection和其子类list、set 进行迭代的迭代器
0x01
具备的方法有:
void remove(): collection中移除迭代器返回的最后一个元素
Enumeration next(): ①指针下移 ②将下移以后集合位置上的元素返回
boolean hasNext():调用next方法如果next抛出NoSuchElementException异常时
返回为float
GOF给迭代器模式的定义为:提供一种方法访问一个容器(container)对象中各个元
素,而又不需暴露该对象的内部细节。
迭代器模式,就是为容器而生
集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合
的第一个元素之前。
如果还未调用next()或在上一次调用 next 方法之后已经调用了 remove 方法,
再调用remove都会报IllegalStateException。
0x02
ListIterator<E>继承了Iterator<E>
ListIterator是只能用于list集合
public static void main(String[] args) {
Collection coll=new ArrayList();
coll.add("tom");
coll.add("Mat");
coll.add("all");
Iterator c = coll.iterator();
List<String> list=new ArrayList<String>();
list.addAll(coll);
ListIterator<String> st = list.listIterator();
while (st.hasNext()){
System.out.println(st.next());
}
System.out.println("----------------");
while (st.hasPrevious()){
System.out.println(st.previous());
}
}
void add(E e): 将指定的内容插入集合中
E previous():①指针上移 ②将上移以后集合位置上的元素返回
如果没有上一个元素的话;就会抛出NoSuchElementException
boolean hasPrevious():
void set(E e):用指定的内容(e)替换next或prverious
ListIterator有add()方法,可以向List中添加对象,而Iterateor不能
ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。Iterator就不可以。
ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能。