Java迭代器

Iterator接口的使用方法

public class IteratorDemo {
	public static void main(String[] args) {
		Collection<String> coll = new ArrayList<String>();	//多态
		coll.add("abc1");
		coll.add("abc2");
		coll.add("abc3");
		coll.add("abc4");
		// 迭代器,对集合ArrayList中的元素进行取出
		// 调用集合的方法iterator()获取Iterator接口的实现类的对象
		Iterator<String> it = coll.iterator();
		// 接口实现类对象,调用方法hasNext()判断集合中是否有元素
		// boolean b = it.hasNext();
		// System.out.println(b);
		// 接口的实现类对象,调用方法next()取出集合中的元素
		// String s = it.next();
		// System.out.println(s);

		// 迭代是反复内容,使用循环实现,循环的终止条件:集合中没元素, hasNext()返回了false
		while (it.hasNext()) {
			String s = it.next();
			System.out.println(s);
		}
	}
}

在这里插入图片描述

迭代器的转型

//集合可以存储任意类型的对象
//当集合中不用泛型指定存储的数据类型时,集合什么都存。
Collection coll = new ArrayList();
coll.add("abc");
coll.add("def");
coll.add("opq");
//获取迭代器
Iterator it = coll.iterator();
while (it.hasNext()) {
	// it.next()获取出来的对象数据类型为Object
	//Object obj = it.next();
	//当需要使用子类对象特有方法时,需要向下转型
	String str = (String) it.next();
 	System.out.println(str.length());
}

//注意:如果集合中存放的是多种对象,这时进行向下转型会发生类型转换异常。

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值