迭代器的作用是统一各种不同容器的访问方式
Iterator
//代码需下载Java编程思想的源码,并修改classpath;
import typeinfo.pets.*;
import java.util.*;
public class Pet1{
public static void main(String[] args){
ArrayList pet = Pets.arrayList(12);//产生一系列随机的pet对象
Iterator it = pet.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
//输出结果:
//Rat
//Manx
//Cymric
//Mutt
//Pug
//Cymric
//Pug
//Manx
//Cymric
//Rat
//EgyptianMau
//Hamster
Iterator的使用:
1.使用容器的iterator()返回一个迭代器对象
2.next()获得序列中的下一个元素,并把指针后移
3.remove()移除刚从容器中取出的元素。
4.hasNext()判断接下来是否还有元素.
ListIterator
ListIterator的指针可以这样理解:每次都指向两个元素的中间位置,因此,若链表中有n个元素,则有n+1个指针的位置。配上官网的解释图片
List中的元素: Element(0) Element(1) Element(2) ... Element(n-1)
cursor positions: ^ ^ ^ ^ ^ (n+1)个指针位置
ListIterator比Iterator更加灵活,可以前后移动
除了拥有Iterator的所有函数,还新加了一些函数:
previous():返回前一个元素,指针前移
set()将最近从容器取出来的元素替换
nextIndex()返回next()要返回元素的下标,如果指针在最后位置(即next()不能返回元素了),则返回链表大小
previousIndex()返回previous()要返回元素的下标,如果指针在第一个位置,则返回-1
add()在下一个next()返回的元素之前,下一个previous()返回的数之后插入一个元素
Note:add()加入的数不会被下一个next()返回。add()完成后,光标自动后移一位到插入元素的后面
import java.util.LinkedList;
import java.util.ListIterator;
public class Insert{
public static void main(String[] args){
LinkedList array = new LinkedList();
for(int i=0;i<10;i++)
array.add(i);
ListIterator it = array.listIterator(0);
while(it.hasNext()){
int num=it.next();
if(num==5){
it.add(100);//在5和6之间插入100
}
System.out.print(num+" ");
}
System.out.println();
it = array.listIterator(0);
//输出array链表的内容
while(it.hasNext())
System.out.print(it.next()+" ");
System.out.println();
}
}
//运行结果:
//ly@ly-HP:~/TIJ4/exercise/holding$ java Insert
//0 1 2 3 4 5 6 7 8 9
//0 1 2 3 4 5 100 6 7 8 9
可以看到在插入后的下个循环中next()返回6而不是100
但链表中没有元素时,add()插入一个元素,然后立马调用next(),编译器会抛出异常,因为此时光标在元素后方。光标之后没有元素