JavaSE_34th_Iterator接口

来源:互联网 发布:淘宝电脑显示屏 编辑:程序博客网 时间:2024/05/30 05:28
一、Iterator接口
1、所有实现了Collection接口的容器类都有一个iterator方法用以返回一个实现了Itrerator接口的对象。
2、Iterator对象称作迭代器,用以方便的实现对容器内元素的遍历操作。
3、Iterator接口定义了如下方法:
boolean hasNext();//判断游标右边是否有元素Object next();//返回游标右边的元素并将游标移动到下一个位置void remove();//删除游标左面的元素,在执行完next之后该操作只能执行一次
4、Iterator方法举例
1)迭代器输出
package com.hpe.container;import java.util.Collection;import java.util.HashSet;import java.util.Iterator;public class TestIterator {public static void main(String[] args) {Collection c = new HashSet();c.add(new Name("f1", "l1"));c.add(new Name("f2", "l2"));c.add(new Name("f3", "l3"));c.add(new Name("f4", "l4"));c.add(new Name("f5", "l5"));c.add(new Name("f6", "l6"));c.add(new Name("f7", "l7"));Iterator i = c.iterator();while(i.hasNext()) {Name n = (Name)i.next();System.out.print(n.getFirstName() + " ");}}}
运行结果:
f6 f7 f1 f2 f3 f4 f5 
2)使用Iterator对象的remove方法
Iterator对象的remove方法是在迭代过程中删除元素的唯一安全方法。
package com.hpe.container;import java.util.Collection;import java.util.HashSet;import java.util.Iterator;public class TestIteratorRemove {public static void main(String[] args) {Collection c = new HashSet();c.add(new Name("fff1", "lll1"));c.add(new Name("f2", "l2"));c.add(new Name("fff3", "lll3"));Iterator i = c.iterator();while(i.hasNext()) {Name n = (Name)i.next();if(n.getFirstName().length() < 3) {i.remove();}}System.out.println(c);}}
运行结果:

[fff3 lll3, fff1 lll1]





0 0
原创粉丝点击