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.

原文地址:https://www.cnblogs.com/yixianyixian/p/7687492.html