Iterator迭代器,集合专用的遍历方式

1.集合类Collection的概述
2.Collection集合遍历以及集合转数组遍历
3.Collection存储自定义对象并遍历练习
4.Iterator迭代器,集合专用的遍历方式
5.Iterator集合迭代器遍历练习

Iterator迭代器,集合专用的遍历方式

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/*	Iterator iterator():迭代器,集合的专用遍历方式
 * 		Object next():获取元素,并移动到下一个位置。
 * 			NoSuchElementException:没有这样的元素,因为你已经找到最后了。
 * 		boolean hasNext():如果仍有元素可以迭代,则返回 true。(
 */
public class IteratorDemo {
	public static void main(String[] args) {
		// 创建集合对象
		Collection c = new ArrayList();

		// 创建并添加元素
		// String s = "hello";
		// c.add(s);
		c.add("hello");
		c.add("world");
		c.add("java");

		// Iterator iterator():迭代器,集合的专用遍历方式
		Iterator it = c.iterator(); // 实际返回的肯定是子类对象,这里是多态

		// Object obj = it.next();
		// System.out.println(obj);
		// System.out.println(it.next());
		// System.out.println(it.next());
		// System.out.println(it.next());
		// System.out.println(it.next());
		// 最后一个不应该写,所以,我们应该在每次获取前,如果有一个判断就好了
		// 判断是否有下一个元素,有就获取,没有就不搭理它

		// if (it.hasNext()) {
		// System.out.println(it.next());
		// }
		// if (it.hasNext()) {
		// System.out.println(it.next());
		// }
		// if (it.hasNext()) {
		// System.out.println(it.next());
		// }
		// if (it.hasNext()) {
		// System.out.println(it.next());
		// }
		// if (it.hasNext()) {
		// System.out.println(it.next());
		// }

		// 最终版代码
		while (it.hasNext()) {
			// System.out.println(it.next());
			String s = (String) it.next();
			System.out.println(s);
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值