Java枚举和迭代器的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/948194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:25:44  来源:igfitidea点击:

Difference between Java Enumeration and Iterator

javacollectionsiteratorenumeration

提问by cometta

What is the exact difference between these two interfaces? Does Enumerationhave benefits over using Iterator? If anyone could elaborate, a reference article would be appreciated.

这两个接口之间的确切区别是什么?是否Enumeration有过使用效益Iterator?如果有人可以详细说明,将不胜感激参考文章。

采纳答案by coobird

Looking at the Java API Specification for the Iteratorinterface, 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 Enumerationand Iteratorwill give successive elements, but Iteratoris improved in such a way so the method names are shorter, and has an additional removemethod. Here is a side-by-side comparison:

底线是,EnumerationIterator都将给出连续的元素,但Iterator以这样的方式进行了改进,因此方法名称更短,并且有一个额外的remove方法。这是一个并排的比较:

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

As also mentioned in the Java API Specifications, for newer programs, Iteratorshould be preferred over Enumeration, as "Iterator takes the place of Enumeration in the Java collections framework." (From the Iteratorspecifications.)

正如 Java API 规范中所提到的,对于较新的程序,Iterator应该优先于Enumeration,因为“迭代器取代了 Java 集合框架中的枚举”。(来自Iterator规格。)

回答by Uri

"Officially", they are supposed to be similar with the iterator interface supporting extra operations (e.g., 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. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.

注意:此接口的功能由 Iterator 接口复制。此外,Iterator 添加了一个可选的删除操作,并具有较短的方法名称。新的实现应该考虑使用 Iterator 而不是 Enumeration。

回答by Licky Lindsay

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 stillimplement Iterable so people can use your class in for loops.

如果出于某种原因(我无法想到)您正在创建一个与 java.util.Collection 或 java.util.Map 没有任何关系的自定义集合类,您仍然应该实现 Iterable 以便人们可以使用你的课程在 for 循环中。

回答by bnguyen82

The main different is Enumeration doesn't expose remove() method. 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. If we need only navigation ignoring such a synchronization, just use Enumeration.

主要的不同是 Enumeration 不公开 remove() 方法。此外,迭代器不允许对底层对象同时进行导航和修改。他们可以控制查看是否有并发修改等,因此需要更多的处理。所以 Enumeration 的性能实际上比 Iterator 快 50%。如果我们只需要忽略这种同步的导航,只需使用枚举。

回答by pavan kumar

Both iterator and enumeration are used to retrieve the data, the difference is that enumeration can be used only for legacy classes i.e vector/stack whereas iterators can be used for the rest. Enumeration can also be used for the key set in maps.

迭代器和枚举都用于检索数据,区别在于枚举只能用于遗留类,即向量/堆栈,而迭代器可用于其余类。枚举也可用于映射中的键集。

回答by shaILU

Iterators are fail-fast. i.e. 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. 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.

迭代器是快速失败的。即,当一个线程通过添加/删除操作更改集合,而另一个线程通过 Iterator usinghasNext() or next()方法遍历它时,迭代器会通过 throwing 快速失败ConcurrentModificationException。迭代器的快速失败行为只能用于检测错误。Hashtable、Vector 等类的方法返回的枚举不是快速失败的,这是通过同步nextElement()锁定当前 Vector 对象的方法内的代码块来实现的,这会花费大量时间。

回答by Earth Engine

One simple fact but haven't mentioned in previous answers is that Iterator<T>is used with Iterable<T>to serve in interpreting for(_type_ element:collection){...}structure.

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

回答by Vipin Jain

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.
3. Two Method are available

2. 可以执行读操作,不能删除元素。
3. 两种方法可用

  • public boolean hasNextElement();
  • public Object nextElement();
  • 公共布尔 hasNextElement();
  • 公共对象 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();
    • public Object next();
    • public void remove();
  1. 它适用于所有收藏

    Iterator itr = c.iterator();  
    where c is any `Collection` class
    
  2. 可以执行读取和删除操作

  3. 三种方法可用

    • 公共布尔 hasNext();
    • 公共对象 next();
    • 公共无效删除();

Limitionin both

Limition两个

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

回答by Jay Sheth

Enumeration can be used only for the legacy class(Vector, Stack...), while Iterator can be used for all.

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

回答by Dhirendra Gautam

1) The main difference between Iterator and Enumeration is removal of the element while traversing the collection. Iterator can remove the element during traversal of collection as it has remove() method. Enumeration does not have remove() method.

1) Iterator 和 Enumeration 的主要区别在于遍历集合时移除元素。迭代器可以在遍历集合期间移除元素,因为它具有 remove() 方法。枚举没有 remove() 方法。

2) Enumeration is fail-safe in nature. It does not throw ConcurrentModificationException if Collection is modified during the traversal. Iterator is fail-fast in nature. It throws ConcurrentModificationException if a Collection is modified while iterating other than its own remove() method.

2) 枚举本质上是故障安全的。如果在遍历过程中修改了 Collection,则不会抛出 ConcurrentModificationException。迭代器本质上是快速失败的。如果在迭代它自己的 remove() 方法以外的时候修改了一个集合,它会抛出 ConcurrentModificationException。

3) Enumeration is a legacy interface which is used for traversing Vector, Hashtable. Iterator is not a legacy interface. Iterator can be used for the traversal of HashMap, LinkedList, ArrayList, HashSet, TreeMap, TreeSet .

3) Enumeration 是一个遗留接口,用于遍历 Vector、Hashtable。迭代器不是遗留接口。Iterator 可用于 HashMap、LinkedList、ArrayList、HashSet、TreeMap、TreeSet 的遍历。