Difference between Java Enumeration and Iterator
Looking at the Java API Specification for the Iterator
interface, there is an explanation of the differences between 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. 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." (From the Iterator
specifications.)
Java Enumeration vs Iterator
Enumeration doesn't throw ConcurrentModificationException , why?
Because there is no path in the code being invoked which throws this exception. Edit: I am referring to the implementation provided by the Vector class, not about the Enumeration interface in general.
Why is this such behavior . Can we say that Enumerator is thread safe.
It is thread-safe in a sense that the code executed is properly synchronized. However, I don't think the result your loop yields is what you would except.
The reason for your output is that the Enumeration object maintains a counter, which is incremented after every invokation of nextElement()
. This counter is not aware of your invokation of remove()
.
Distinction between iterator and enumerator
Iterating means repeating some steps, while enumerating means going through all values in a collection of values. So enumerating usually requires some form of iteration.
In that way, enumerating is a special case of iterating where the step is getting a value from a collection.
Note the "usually" – enumerating may also be performed recursively, but recursion and iteration are so closely related that I would not care about this small difference.
You may also enumerate values you do not explicitly store in a collection. For example, you can enumerate the natural number, primes, or whatever but you would calculate these values during the enumeration and not retrieve them from a physical collection. You understand this case as enumerating a virtual collection with its values defined by some logic.
I assume Reed Copsey got the point. In C# there are two major ways to enumerate something.
- Implement
Enumerable
and a class implementingIEnumerator
- Implement an iterator with the
yield
statement
The first way is harder to implement and uses objects for enumerating. The second way is easier to implement and uses continuations.
How to use Iterator/Enumeration Interface in Java
Enumerators are part of legacy Java 1.0. Iterators only appeared in Java 1.2. To my knowledge, Enumerators are only kept for backward compatibility. As per the java docs for Enumerator, all new code should user the Iterator interface.
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.
You should use Iterators when looping through a collection, list, set, etc or something that implements that Iterator interface. You can also use the "new" (Java 5) for loop construct to iterate over such a collection. Keep in mind, however, that the only safe way to remove an item from a collection when looping is to use the Iterator.remove() method.
Confusion about collections, enumeration, and iterator in Java
You are confused between several different classes.
enum
Enumeration
Iterator
An enum
is an enumerated constant, i.e. a constant that can take several defined values such as
public enum Gender {
MALE,
FEMALE;
}
It is designed to provide type safety.
An Enumeration
is a now deprecated part of the Collection
s API - forget about this. It is superseded by Iterator
.
An Iterator
is an implementation of the Iterator Pattern as described by the Gang of Four.
For why to use an Iterator
rather than a Collection
maybe my answer here will help.
As for enums of people in the format of name(String description, int age), and that's how he defined his constructor and he had get and set methods. This is a big no-no.
An enum
should be a constant so should not have setter
methods. An enum
is a set of defined values like in my example above.
If you want a Collection
of people
then a Person
class in a Collection<Person>
would be the correct solution.
So, in summary. Use an enum
for constant values; use a Collection
for, well, collections of things. And do not use an Enumeration
- forget it exists at all.
Instances of Iterator, ListIterartor and Enumeration
You didn't get anonymous classes of Vector
in the first two cases (java.util.Vector$Itr
and java.util.Vector$ListItr
). java.util.Vector$something
indicates that something
is a class nested inside the java.util.Vector
class. Anonymous classes have no name. Itr
and ListItr
are class names, so they are definitely not anonymous.
The only case in which you did get an anonymous class instance is in v.elements()
, since Vector
's elements()
method returns an anonymous class instance that implements the Enumeration
interface :
public Enumeration<E> elements() {
return new Enumeration<E>() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return (E)elementData[count++];
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
Related Topics
Why Are Interface Method Invocations Slower Than Concrete Invocations
Java:Does Wait() Release Lock from Synchronized Block
Why Is System.Arraycopy Native in Java
Steps Needed to Use MySQL Database with Play Framework 2.0
Block()/Blockfirst()/Blocklast() Are Blocking Error When Calling Bodytomono After Exchange()
Unsatisfieddependencyexception: Error Creating Bean with Name
Collections.Synchronizedlist and Synchronized
Java: How to Create a Movie from an Array of Images
How to Read File from Zip Using Inputstream
How to Convert Set<String> to String[]
Convert Localdate to Localdatetime or Java.Sql.Timestamp
Does Java Have Any Mechanism for a Vm to Trace Method Calls on Itself, Without Using Javaagent, etc
Java 8 Stream with Batch Processing
Why Does Java App Crash in Gdb But Runs Normally in Real Life