简体   繁体   English

Java枚举和迭代器的区别

[英]Difference between Java Enumeration and Iterator

What is the exact difference between these two interfaces?这两个接口之间的确切区别是什么? Does Enumeration have benefits over using Iterator ? Enumeration比使用Iterator有好处吗? If anyone could elaborate, a reference article would be appreciated.如果有人可以详细说明,将不胜感激参考文章。

Looking at the Java API Specification for the Iterator interface, there is an explanation of the differences between Enumeration :查看Iterator接口的 Java API 规范,有对Enumeration之间差异的解释:

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 improved the method names by shortening away the verbiage, and it has an additional remove method.最重要的是, EnumerationIterator都会给出连续的元素,但Iterator通过缩短措辞改进了方法名称,并且它有一个额外的remove方法。 Here is a side-by-side comparison:这是一个并排的比较:

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

As also mentioned in the Java API Specifications, for newer programs, Iterator should be preferred over Enumeration , as "Iterator takes the place of Enumeration in the Java collections framework."正如 Java API 规范中所提到的,对于较新的程序, Iterator应该优先于Enumeration ,因为“Iterator 取代了 Java 集合框架中的 Enumeration”。 (From the Iterator specifications.) (来自Iterator规范。)

Iterators are fail-fast .迭代器是快速失败的 ie when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException .即,当一个线程通过添加/删除操作更改集合,而另一个线程使用hasNext() or next()方法通过 Iterator 遍历它时,迭代器会通过抛出ConcurrentModificationException迅速失败。 The fail-fast behavior of iterators can be used only to detect bugs.迭代器的快速失败行为只能用于检测错误。 The Enumerations returned by the methods of classes like Hashtable, Vector are not fail-fast that is achieved by synchronizing the block of code inside the nextElement() method that locks the current Vector object which costs lots of time.由 Hashtable、Vector 等类的方法返回的枚举不是快速失败的,这是通过同步nextElement()方法内的代码块来实现的,该方法锁定当前的 Vector 对象,这会花费大量时间。

"Officially", they are supposed to be similar with the iterator interface supporting extra operations (eg, removal). “正式地”,它们应该类似于支持额外操作(例如,删除)的迭代器接口。 Generally, the tendency is to use iterators.通常,倾向于使用迭代器。

Here is from the enumeration interface javadocs :这是来自枚举接口 javadocs

NOTE: The functionality of this interface is duplicated by the Iterator interface.注意:此接口的功能由 Iterator 接口复制。 In addition, Iterator adds an optional remove operation, and has shorter method names.此外,Iterator 添加了一个可选的删除操作,并具有较短的方法名称。 New implementations should consider using Iterator in preference to Enumeration.新的实现应该考虑使用 Iterator 而不是 Enumeration。

一个简单但在之前的答案中没有提到的事实是Iterator<T>Iterable<T>一起用于解释for(_type_ element:collection){...}结构。

There is basic three difference in Enumeration and Iterator枚举和迭代器有基本的三个区别

Enumeration枚举
1. it is use for only lagacy class(eg. Vector ) 1. 它仅用于滞后类(例如Vector

    Enumeration e = v.elements();  
    v is the object of `Vector` class

2. Read operation can be perform, we can not remove element. 2. 可以执行读操作,不能删除元素。
3. Two Method are available 3. 两种方法可用

  • public boolean hasNextElement();公共布尔 hasNextElement();
  • public Object nextElement();公共对象 nextElement();

Iterator迭代器

  1. it is applicable for all Collection它适用于所有收藏

    Iterator itr = c.iterator(); where c is any `Collection` class
  2. Read and Remove operation can be perform可以执行读取和删除操作

  3. Three Method are available三种方法可用

    • public boolean hasNext();公共布尔 hasNext();
    • public Object next();公共对象 next();
    • public void remove();公共无效删除();

Limition in both Limition两个

  • Move only forward direction仅向前移动
  • There is no any methods for Add object and Replace object Add objectReplace object没有任何方法

1) The main difference between Iterator and Enumeration is removal of the element while traversing the collection. 1) Iterator 和 Enumeration 的主要区别在于遍历集合时移除元素。 Iterator can remove the element during traversal of collection as it has remove() method.迭代器可以在遍历集合期间移除元素,因为它具有 remove() 方法。 Enumeration does not have remove() method.枚举没有 remove() 方法。

2) Enumeration is fail-safe in nature. 2) 枚举本质上是故障安全的。 It does not throw ConcurrentModificationException if Collection is modified during the traversal.如果在遍历过程中修改了 Collection,则不会抛出 ConcurrentModificationException。 Iterator is fail-fast in nature.迭代器本质上是快速失败的。 It throws ConcurrentModificationException if a Collection is modified while iterating other than its own remove() method.如果在迭代它自己的 remove() 方法以外的时候修改了一个集合,它会抛出 ConcurrentModificationException。

3) Enumeration is a legacy interface which is used for traversing Vector, Hashtable. 3) Enumeration 是一个遗留接口,用于遍历 Vector、Hashtable。 Iterator is not a legacy interface.迭代器不是遗留接口。 Iterator can be used for the traversal of HashMap, LinkedList, ArrayList, HashSet, TreeMap, TreeSet . Iterator 可用于 HashMap、LinkedList、ArrayList、HashSet、TreeMap、TreeSet 的遍历。

If you're writing your own collection class, and you're extending any of the existing classes or implementing any of the Collections framework interfaces, you basically have no choice but to use Iterator.如果您正在编写自己的集合类,并且要扩展任何现有类或实现任何集合框架接口,则基本上别无选择,只能使用 Iterator。

If for some reason (that I can't think of) you're creating a custom collection class that does not relate to java.util.Collection or java.util.Map in any way, you should still implement Iterable so people can use your class in for loops.如果出于某种原因(我无法想到)您正在创建一个与 java.util.Collection 或 java.util.Map 没有任何关系的自定义集合类,您仍然应该实现 Iterable 以便人们可以使用你的课程在 for 循环中。

The main different is Enumeration doesn't expose remove() method.主要的不同是 Enumeration 不公开 remove() 方法。 Moreover, Iterator don't allow a simultaneously navigation and modification on an underlying object.此外,迭代器不允许对底层对象同时进行导航和修改。 They have a control to see if there are concurrent modifications or so, and hence takes more processing.他们可以控制查看是否有并发修改等,因此需要更多的处理。 So Enumeration's performance is virtually 50% faster than Iterator.所以 Enumeration 的性能实际上比 Iterator 快 50%。 If we need only navigation ignoring such a synchronization, just use Enumeration.如果我们只需要忽略这种同步的导航,只需使用枚举。

Enumeration 只能用于遗留类(Vector, Stack...),而 Iterator 可以用于所有。

Both iterator and enumeration are used to retrieve the data, the difference is that enumeration can be used only for legacy classes ie vector/stack whereas iterators can be used for the rest.迭代器和枚举都用于检索数据,区别在于枚举只能用于遗留类,即向量/堆栈,而迭代器可用于其余类。 Enumeration can also be used for the key set in maps.枚举也可用于映射中的键集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM