What is the exact difference between these two interfaces? Does Enumeration
have benefits over using Iterator
? If anyone could elaborate, a reference article would be appreciated.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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.
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 throwingConcurrentModificationException
. 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 thenextElement()
method that locks the current Vector object which costs lots of time.Looking at the Java API Specification for the
Iterator
interface, there is an explanation of the differences betweenEnumeration
:The bottom line is, both
Enumeration
andIterator
will give successive elements, butIterator
is improved in such a way so the method names are shorter, and has an additionalremove
method. Here is a side-by-side comparison:As also mentioned in the Java API Specifications, for newer programs,
Iterator
should be preferred overEnumeration
, as "Iterator takes the place of Enumeration in the Java collections framework." (From theIterator
specifications.)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.
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.
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.
"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: