What is the difference between
Enumeration and Iterator?
Enumeration
Ø When the Enumeration interface is
implemented by an object, that object can generate a sequence of elements.
Ø This was introduced in JDK 1.0 .
Ø The method hasMoreElements() will
test if this enumeration contains more elements and the nextElement() returns
the next element in the sequence (if there is at least one more to go).
Example:-
Enumeration
e = v1.elements();// v1 is an object of Vector
while(e.hasMoreLements()){
System.out.println(e.nextElement());
}
Iterator
Which allows
iterating through elements of the collections objects that implement the
Collections framework (such as ArrayList, LinkedList, etc.).
Ø This was introduced in JDK 1.2 and
replaced the Enumerator within the Java Collections Framework.
Ø Unlike Enumeration, Iterator is
fail-safe.This means that concurrent modifications (to the underlying
collection) are not allowed when Iterator is used.
Ø This is very useful in multi-threaded
environments where there is always a risk of concurrent modifications.
Ø In the event of a concurrent
modification, the Iterator object will throw a ConcurrentModificationException.
Ø Iterator has shorter method names
compared to Enumerator.
Ø Furthermore, iterator has the
additional functionality of deleting elements during the iteration (which is
not possible using Enumerator).
Ø So, if there is a need to remove
elements from the collection, Iterator is the only option that can be
considered.
Example:-
Iterator i =
v1.elements();// v1 is an object of Vector
while(i.hasNext()){
System.out.println(e.next());
}
No comments:
Post a Comment