------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
//: holding/SimpleIteration.java
importtypeinfo.pets.*;
importjava.util.*;
public classSimpleIteration {
public static void main(String[] args) {
List<Pet> pets = Pets.arrayList(12);
Iterator<Pet> it = pets.iterator();
while(it.hasNext()) {
Pet p = it.next();
System.out.print(p.id() + ":" +p + " ");
}
System.out.println();
// A simpler approach, when possible:
for(Pet p : pets)
System.out.print(p.id() + ":" +p + " ");
System.out.println();
// An Iterator can also remove elements:
it = pets.iterator();
for(int i = 0; i < 6; i++) {
it.next();
it.remove();
}
System.out.println(pets);
}
} /* Output:
0:Rat 1:Manx2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 8:Cymric 9:Rat 10:EgyptianMau11:Hamster
0:Rat 1:Manx2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 8:Cymric 9:Rat 10:EgyptianMau11:Hamster
[Pug, Manx,Cymric, Rat, EgyptianMau, Hamster]
*///:~
迭代器是一个对象,他的工作是遍历并选择序列中的对象,而客户端程序员不必知道或关心该序列底层的结构。java的Iterator只能单向移动,这个Iterator只能来:
1 使用方法iterator()要求容器返回一个Iterator。Iterator将准备好返回序列的第一个元素。
2 使用next()获得序列的下一个元素。
3 使用hasNext()将检查序列中是否还有元素。
4 使用remove()将迭代器新近返回的元素删除。