Iterator接口

注:

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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值