Points To Remember
- In java 1.0, there were two primary collection classes HashMap and Vector.
- Enumeration was a class in Java 1.0 to Iterate through these collection classes.(They are not the enum types.)
- Iterator was introduced in Java 1.2
Difference between Enumeration and Iterator.
Enumeration | Iterator |
---|---|
It was introduces in Java v1.0 | It was introduced in java v1.2 |
Enumeration does not have remove() method | Iterator has remove() method |
Enumeration provides a read only iteration over collection | Iterator provides iteration over collections along with manipulation of objects like adding and removing from object. |
Enumeration is less safe and secure | Iterator is more secure and safe, when multiple thread work on same object, it does not allow any thread to modify the object and throws ConcurrentModificationException. |
Enumeration has lengthy method names like
| Iterator have short method names like
|
Enumeration is used when we want to iterate Collection object in read only manner. | Iterator is used when we want to iterate on collection object along with object manipulation. |
Using Enumeration to Iterate.
Vector names = new Vector();
// ... add some names to the collection
Enumeration e = names.elements();
while (e.hasMoreElements())
{
String name = (String) e.nextElement();
System.out.println(name);
}
Using Iterator to Iterate.
List names = new LinkedList();
// ... add some names to the collection
Iterator i = names.iterator();
while (i.hasNext())
{
String name = (String) i.next();
System.out.println(name);
}
Comments
Post a Comment