关于Iterator接口(迭代器)

来源:互联网 发布:移动硬盘不能写入 mac 编辑:程序博客网 时间:2024/06/14 07:08

public interface Iterator
对 collection 进行迭代的迭代器。迭代器取代了 Java Collections Framework 中的 Enumeration。

迭代器与枚举有两点不同:
1.迭代器允许调用者利用定义良好的语义在迭代期间从迭代器所指向的 collection 移除元素。
2.方法名称得到了改进

所有是实现Collection接口的容器类都有一个iterator方法用来返回一个iterator接口的对象。
iterator接口中只有三个方法:
boolean hasNext(); 判断游标右边是否有元素
Object next(); 返回游标右边的元素并将游标移动到下一位
void remove(); 删除游标左边的元素,在执行完next操作之后该操作只能执行一次。

实例

public class iteratorDemo2 {    public static void main(String[] args) {        Collection c = new HashSet();        c.add("ni");        c.add("nihao");        c.add("hello");        System.out.println(c);        Iterator i = c.iterator();        while (i.hasNext()){         //遍历,当存在下一个元素的时候返回true            String str =(String) i.next();        //i.next();获取下一个元素并强制转换成String类型            if(str.length() < 3){            //当元素的长度小于3 移除                i.remove();                //c.remove(str);                //如果换成c.remove(name);会产生例外;                //java.util.ConcurrentModificationException                //因为在循环的内部,Iterator会执行锁定,不让外部进行访问             }        }        System.out.println(c);    }}

与增强的for循环比较
增强for循环的缺陷
1.数组:不能方便的访问数组的下标值
2.集合:与iterator相比不能方便的删除集合中的内容。在内部也只是调用Iterator
一般建议使用Iterator

1 0
原创粉丝点击