java:我们对Iterator理解错了

本文介绍了一种用于遍历不同容器的设计模式——迭代器,并通过示例展示了如何利用迭代器模式来实现对ArrayList、LinkedList、HashSet及TreeSet等集合数据的统一访问。此外,还提供了迭代器与for循环结合使用的实例。

Iterator是解决不同容器的一种设计模型,同时支持ArrayList、LinkedList、HashSet、TreeSet集合数据的迭代。


image.png

import typeinfo.pets.;
import java.util.
;
public class CrossContainerIteration {
public static void display(Iterator<Pet> it) {
while(it.hasNext()) {
Pet p = it.next();
System.out.print(p.id() + ":" + p + " ");
}
System.out.println();
}
public static void main(String[] args) {
ArrayList<Pet> pets = Pets.arrayList(8);
LinkedList<Pet> petsLL = new LinkedList<Pet>(pets);
HashSet<Pet> petsHS = new HashSet<Pet>(pets);
TreeSet<Pet> petsTS = new TreeSet<Pet>(pets);
display(pets.iterator());
display(petsLL.iterator());
display(petsHS.iterator());
display(petsTS.iterator());
}
}
/* 输出
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
4:Pug 6:Pug 3:Mutt 1:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat
5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug 0:Rat

还可以与for循环联合使用

List<String> all = new ArrayList<String>(Arrays.asList(insarray));
all.addAll(alist);
Iterator<String> it = all.iterator();
for(int i=0;i<alist.size();i++){
String outstr = it.next();
it.remove();
System.out.print(outstr);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值