注:
iteritor即Collection接口的迭代器
1:所有实现了Collection接口的容器类都有一个iterator方法用以返回一个实现了Iterator接口的对象。
2:Iterator对象称作迭代器,用以方便的实现对容器内元素的遍历操作。
3:Iterator接口定义了如下方法
可以将iteritor看做是游标,指向所在元素的左边。
boolean hasNext(); //判断游标右边是否有元素
Object next(); //返回游标右边的元素并将游标移动到下一个位置
void remove(); //删除游标左边的元素,在执行完next之后,该操作执行一次
***调用Iterator方法时 ,会在栈空间开辟一个空间 ,将返回值装进去。
示例:
import java.util.*;
public class Test {
public static void main(String [] args) {
Collection c = new Hashset();
c.add(new Name("f1","l1"));
c.add(new Name("f2","l2"));
c.add(new Name("f3","l3"));
Iterator i = c.iterator(); //不需要知道对象是什么
while (i.hashNext()) { //当它还有下一个时
//next()的返回值类型为Object类型,需要转换为相应类型
Name n = (Name)i.next(); //强制转换
System.out.print(n.getFirstName()+" ")
}
}
}
输出结果: f1 f2 f3
Iteritor方法举例
1:Iterator对象的remove方法时在迭代过程中删除元素的唯一安全方法。
Collection c = new HashSet();
c.add(new Name ( "fff1" , " lll1" ) );
c.add(new Name ( "f2" , " l2" ) );
c.add(new Name ( "fff3" , " lll3" ) );
for( Iterator i = c.iterator() ; i.hashNext() ; ){
Name name = (Name)i.next(); //强制转换
if(name.getFirstName().length()<3) {
i.remove(); //如果产生c.remove(name); 会产生例外
}
}
System.out.println(c);
输出结果 [ fff3 lll3 , fff1 lll1]