In this post, we'll see what is enumeration and Iterator and differences between them with the help of some examples.
Enumeration
Enumeration is a public interface in Java, introduced in JDK 1.0, which provides the ability to enumerate through sequences of elements. It is found under java.util package.
An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.
Method of Enumeration Class
Example
java
-
latte
.
blogspot
.com
3
2
1
Exception in thread "main" java.util.NoSuchElementException: Hashtable Enumerator
at java.util.Hashtable$Enumerator.nextElement(Unknown Source)
at EnumerationDemo.main(EnumerationDemo.java:28)
Iterator
Iterator is a public interface in Java.util package, 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.
The java.util.Iterator interface allows the iteration of container classes. Each Iterator provides a next() and hasNext() method, and may optionally support a remove() method. Iterators are created by the corresponding container class, typically by a method named iterator().
Additionally, for java.util.List there is a java.util.ListIterator with a similar API but that allows forward and backward iteration, provides its current index in the list and allows setting of the list element at its position.
The J2SE 5.0 release of Java introduced the Iterable interface to support an enhanced for (foreach) loop for iterating over collections and arrays.
Method of Iterator Class
Example
java
-
latte
blogspot
.
com
java
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at IteratorDemo.main(IteratorDemo.java:22)
Difference between Enumeration and Iterator
Both are interface,not an implementation, and even new libraries sometimes still use the old Enumeration.
From the above discussion, following differences are clear.
Iterator remove() method example
Array Size= 6
java
-
latte
blogspot
.
com
Array Size= 0
Note: One point to remember while using remove() method, if you call remove() before hasNext() java.lang.IllegalStateException will occur.
In addition, you can produce an Enumeration for any Collection by using the Collections.enumeration() method, as seen in the following example:
java
-
latte
blogspot
.
com
Related Post
How to iterate over Map in 4 ways
Over of Java Collection Framework
If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...
Enumeration
Enumeration is a public interface in Java, introduced in JDK 1.0, which provides the ability to enumerate through sequences of elements. It is found under java.util package.
An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.
Method of Enumeration Class
Method | Description | Exception |
boolean hasMoreElements() | Tests if this enumeration contains more elements.element to provide; false otherwis | |
E nextElement() | Returns the next element of this enumeration if this enumeration object has at least one more element to provide. | NoSuchElementException - if no more elements exist. |
Example
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
public class EnumerationDemo {
public static void main(String[] javalatte) {
Vector<String> l = new Vector<String>();
l.add("java");
l.add("-");
l.add("latte");
l.add(".");
l.add("blogspot");
l.add(".com");
Enumeration<String> en = l.elements();
while(en.hasMoreElements()){
System.out.println(en.nextElement());
}
System.out.println();
Hashtable<String, String> ht = new Hashtable<String,String>();
ht.put("java", "1");
ht.put("latte", "2");
ht.put("blogspot", "3");
ht.put("com", "4");
Enumeration<String> enHash = ht.elements();
while(enHash.hasMoreElements()){
System.out.println(enHash.nextElement());
ht.remove("com"); // you can remove while iterating and no ConcurrentModificationException
}
System.out.println(enHash.nextElement()); // thows NoSuchElementException as not element exist.
}
}
Sample Outputjava
-
latte
.
blogspot
.com
3
2
1
Exception in thread "main" java.util.NoSuchElementException: Hashtable Enumerator
at java.util.Hashtable$Enumerator.nextElement(Unknown Source)
at EnumerationDemo.main(EnumerationDemo.java:28)
Iterator
Iterator is a public interface in Java.util package, 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.
The java.util.Iterator interface allows the iteration of container classes. Each Iterator provides a next() and hasNext() method, and may optionally support a remove() method. Iterators are created by the corresponding container class, typically by a method named iterator().
Additionally, for java.util.List there is a java.util.ListIterator with a similar API but that allows forward and backward iteration, provides its current index in the list and allows setting of the list element at its position.
The J2SE 5.0 release of Java introduced the Iterable interface to support an enhanced for (foreach) loop for iterating over collections and arrays.
Method of Iterator Class
Method | Description | Exception |
boolean hasNext() | Returns true if the iteration has more elements. | |
E next() | Returns the next element in the iteration | NoSuchElementException - if no more elements exist. |
void remove() | Removes from the underlying collection the last element returned by this iterator (optional operation). | UnsupportedOperationException - if the remove operation is not supported by this iterator IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method |
Example
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] javalatte) {
ArrayList<String> ar = new ArrayList<String>();
ar.add("java");
ar.add("-");
ar.add("latte");
ar.add("blogspot");
ar.add(".");
ar.add("com");
Iterator<String> it = ar.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//System.out.println(it.next()); //it throws NoSuchElementException as not element exist.
System.out.println();
Iterator<String> it1 = ar.iterator();
while(it1.hasNext()){
System.out.println(it1.next());
ar.remove(3); // it will throw ConcurrentModificationException
}
}
}
Sample Outputjava
-
latte
blogspot
.
com
java
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at IteratorDemo.main(IteratorDemo.java:22)
Difference between Enumeration and Iterator
Both are interface,not an implementation, and even new libraries sometimes still use the old Enumeration.
From the above discussion, following differences are clear.
- Method names have been improved.
Enumeration methods Iterator hasMoreElement() hasNext() nextElement() next() remove() - Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. we'll see example of this next.
- Iterators are fail-fast,when one thread changes the collection with add or remove operations or you modify the collection, while another thread is traversing it through an Iterator using hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException.
- Enumeration is applicable for Legacy Classes.
Iterator remove() method example
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorRemoveDemo {
public static void main(String[] args) {
ArrayList<String> ar = new ArrayList<String>();
ar.add("java");
ar.add("-");
ar.add("latte");
ar.add("blogspot");
ar.add(".");
ar.add("com");
Iterator<String> it = ar.iterator();
System.out.println("Array Size= "+ar.size());
while(it.hasNext()){
System.out.println(it.next());
it.remove();
}
System.out.println("Array Size= "+ar.size());
}
}
Sample OutputArray Size= 6
java
-
latte
blogspot
.
com
Array Size= 0
Note: One point to remember while using remove() method, if you call remove() before hasNext() java.lang.IllegalStateException will occur.
Iterator<String> it = ar.iterator();
it.remove(); // new line in the above code
System.out.println("Array Size= "+ar.size());
while(it.hasNext()){
In addition, you can produce an Enumeration for any Collection by using the Collections.enumeration() method, as seen in the following example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
public class newLatte {
public static void main(String[] args) {
ArrayList<String> ar = new ArrayList<String>();
ar.add("java");
ar.add("-");
ar.add("latte");
ar.add("blogspot");
ar.add(".");
ar.add("com");
Enumeration<String> en = Collections.enumeration(ar);
while(en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
}
Sample outputjava
-
latte
blogspot
.
com
Related Post
How to iterate over Map in 4 ways
Over of Java Collection Framework
If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...