Iterator接口

来源:互联网 发布:大数据盈利点 编辑:程序博客网 时间:2024/05/16 11:31

Iterator接口

Iterator接口

1、所有实现了Collection接口的容器类都有一个iterator方法,用以返回一个实现了Iterator接口的对象;

2、Iterator对象称为迭代器,用以方便的实现对容器内元素的遍历操作;

3、Iterator接口定义了如下方法:

boolean hasNext();  //判断游标的右边是否有元素

Object  next();   //返回游标右边的元素并将游标移动到下一个位置

void remove();   //删除游标左面的元素,

    注:Iterator对象的remove方法是在迭代过程中删除元素的唯一的安全方法。

示例:

public static void main(String[] args){
  Collection c = new HashSet<>();
  c.add(new Integer(1));
  c.add(new Integer(3));
  c.add(new Integer(4));
  Iterator i = c.iterator();
  while (i.hasNext()) {
   Integer in = (Integer) i.next();  //next()的返回值为Object类型,需要将其转换为相应的类型
   System.out.print(in + " ");
  }
 }

运行结果:

1 3 4

0 0
原创粉丝点击