迭代器(iterator)(java)

迭代器是一个对象,也是一种设计模式,用于遍历并选择序列中的对象,而客户端程序员不必知道或关心序列底层的结构。

下面结合《Thinking in Java》里的代码来说明一下迭代器(Iterator)的用法。

public class SimpleIteration {
	public static void main(String[] args) {
		List<Pet> pets = Pets.arrayList(12);
		Iterator<Pet> it = pets.iterator();//因为arrayList实现了iterator接口,所以调用它的iterator()方法便可获得迭代器。
		while (it.hasNext()) {//hasNext()判断是否还有下一个
			Pet p = it.next();//迭代器指向下一个元素
			System.out.print(p.id() + ":" + p + " ");
		}
		System.out.println();
		// 用foreach的方法实现的遍历。
		for (Pet p : pets)
			System.out.print(p.id() + ":" + p + " ");
		System.out.println();
		// 用迭代器实现的删除
		it = pets.iterator();//重新定义it是因为在先前的遍历中it已经不是指向第一个元素了。
		for (int i = 0; i < 6; i++) {
			it.next();
			it.remove();
		}
		System.out.println(pets);
	}
} /*
 * Output: 0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx 8:Cymric
 * 9:Rat 10:EgyptianMau 11:Hamster 0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric
 * 6:Pug 7:Manx 8:Cymric 9:Rat 10:EgyptianMau 11:Hamster [Pug, Manx, Cymric,
 * Rat, EgyptianMau, Hamster]
 */

我们看到用foreach和迭代器的方法都能实现元素的遍历。但在删除元素时要使用迭代器,因为迭代器在进行remove()操作时能对元素个数进行维护(删除时先调用next(),再调用remove()),而foreach语句做不到。

 listIterator是一个功能更强大的迭代器,它不仅能向后移动,还能向前遍历(使用previous())。创建方式与Iterator相同。在创建listIterator时还可以传入参数(listIterator(n)),这样创建了一个一开始就指向列表索引为n的迭代器。






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值