zoukankan      html  css  js  c++  java
  • Java中的迭代迭代器Iterator与枚举器Enumeration

    Iterator 和 Enumeration区别

    Iterator 和 Eumberation都是Collection集合的遍历接口,我们先看下他们的源码接口

    package java.util;
    
    public interface Enumeration<E> {
    
        boolean hasMoreElements();
    
        E nextElement();
    }
    package java.util;
    
    public interface Iterator<E> {
        boolean hasNext();
    
        E next();
    
        void remove();
    }

    1 引入的时间不同

    Iteration是从JDK1.0 开始引入,Enumeration是从JDK1.2开始引入

    2 接口不同

    Enumeration只有2个函数接口。通过Enumeration,我们只能读取集合的数据,而不能对数据进行修改

    Iteration只有3个函数的接口。Iteration除了能读取集合的数据之外,也能对数据进行删除

    Java的API 解析里面对两个接口的不同是这样解释的:

    Iterators differ from enumerations in two ways:

    • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
    • Method names have been improved.

    The bottom line is, both Enumeration and Iterator will give successive elements, but Iterator is improved in such a way so the method names are shorter, and has an additional remove method. Here is a side-by-side comparison:

      Enumeration                     Iterator
      ----------------                ----------------
      hasMoreElement()                hasNext()
      nextElement()                   next()
      N/A                             remove()

    3 Enumeration是历史遗留接口

    Enumeration接口作为一个遗留接口主要用来实现例如 Vextor HashTable Stack 的遍历,而Iterator作为比较新的接口,实现了Collection框架下大部分实现类的遍历比如说 ArrayList LinkedList HashSet LinkedHashSet TreeSet HashMap LinkedHashMap TreeMap 等等

     4 Fail-Fast Vs Fail-Safe

    Iterator支持Fail-Fast机制,当一个线程在遍历时,不允许另外一个线程对数据进行修改(除非调用实现了Iterator的Remove方法)。、

    因此Iterator被认为是安全可靠的遍历方式

    5、应该使用哪个

     还是摘一段JAVA API解析上的一段话(大意就是虽然两个接口的功能是重复的,但是Iterator由于比Enumeration多了remove方法且接口方法名字更短,因此推荐在后面的类中使用Iterator)

    According to Java API Docs, Iterator is always preferred over the Enumeration. Here is the note from the Enumeration Docs.

    NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation,

    and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.

  • 相关阅读:
    thinkphp tp5 常用 functions
    nginx配置虚拟机 vhost 端口号 域名 区分虚拟机
    thinkphp tp5 模板 引擎 字符串 截取 函数 省略 显示
    C++运算符重载
    c++纯虚函数
    c++面向对象模型---c++如何管理类,对象以及它们之间的联系
    c++多态
    c++友元函数
    c语言的函数指针
    c++两种字符串赋值方式 并介绍 C语言下遍历目录文件的方式
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/7687492.html
Copyright © 2011-2022 走看看