Iterator的几个方法及意义

迭代器是一个对象,它的工作时遍历并选择序列中的对象。迭代器通常被称为轻量级对象,因为创建它的代价小,Java的Iterator只能用来单向移动。

4个方法:

1.使用iterator()来返回一个Iterator。

2.使用next()获得序列中的下一个元素。

3.使用hasNext()检查序列中是否还有元素。

4.使用remove()将迭代器新近返回的元素删除。


其实,迭代器除了遍历容器之外,最大的功能就是统一了对容器的访问方式。

完全可以将Itarator作为参数,例如(Java编程思想中的源码):

public class CrossContainerIterator{
public static  void display (Iterator<Pet> it){
  while(it.hasNext()){
  Pet p  = it.next();
System.out.println(p.id+":"+p);
}

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> petTS = new TreeSet<Pet>(pets);
  display(pets.iterator);
  display(petsLL.iterator);
  display(petsHS.iterator);
  display(petsTS.iterator);
 
}
}

由此可看出不用去管具体的容器类型是什么,只要数据类型相同,那么都能使用iterator来进行遍历。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值