Java Enumeration and Iterators

Contributor Icon Contributed by William_Wilson Date Icon February 10, 2006  
Tag Icon Tagged: Java programming

What and how to use Enumerationa and Iterators


Defenitions:
Set: an unordered array of elements or objects
Collection: an ordered set
*Vectors already implement the Collection interface, but you can define your own Collection.
*ArrayLists and Vectors, both support Iterators

Enumeration
An enumeration is an object that generates elements one at a time, used for passing through a collection, usually of unknown size.
The traversing of elements can only be done once per creation.

Enumeration’s have two options:
nextElement() which returns the next object in the collection
hasMoreElements() which returns true, until the last object has been returned by nextElement()

Code Example:
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add(”Sunday”);
dayNames.add(”Monday”);
dayNames.add(”Tuesday”);
dayNames.add(”Wednesday”);
dayNames.add(”Thursday”);
dayNames.add(”Friday”);
dayNames.add(”Saturday”};
days = dayNames.elements();
while (days.hasMoreElements())
System.out.println(days.nextElement()); } }
/*The output will be the days of the week listed in order*/

Enumerations do not allow for the modification of the collection, which is being traversed, thus the Iterators are used if this is required.

Iterators have 3 options:
hasNext() returns true if there is another element in the collection
next() which returns the next object
remove() which removes the last object taken using next()

Code Example:
import java.util.Vector;
import java.util.Iterator;
public class IteratorTester {
public static void main(String args[]) {
String[] num = {”one”, “two”, “three”, “four”, “five”,”six”, “seven”, “eight”, “nine”, “ten”};
Vector aVector = new
Vector(java.util.Arrays.asList(num));
System.out.println(”Before Vector: ” + aVector);
Iterator nums = aVector.iterator();
while(nums.hasNext()) {
String aString = (String)nums.next();
System.out.println(aString);
if (aString.length() > 4)
nums.remove(); }
System.out.println(”After Vector: ” + aVector); } }
/*displays the collection, then removes items with a length greater than 4 and displays again to show the remove feature */

*Why not use for(int i=0; i< v.size();i++){}?
For loops are expensive to the processor when the collection reaches large sizes, as many operations are done just to compute the first line:
int i = 0 is an assignment and creation (2 operations)
i get size, check value of i, and compare (3 operations)
i++ gets i then adds 1 to it [++i is only 2 operations] this one (3 operations)
*7/8 operations in total, each time the loop runs through

where an enumeration or iterator uses a while(){}
while(v.hasNext()) has next true or false (1 operation)
while(v.hasMoreElements()) has more true or false (1 operation)
*Only one operation per repeat of this loop

Questions/Comments as always can be sent to: william_a_wilson@hotmail.com
*OR suggestions for other Java recipes :)

-William. ยง (marvin_gohan)

Previous recipe | Next recipe |
 
  • Mahendra Sahu
    Simple Do this in order to get the size of the Enumeration

    Enumeration e = null; //keep your values
    System.out.println("Size of the Enum is:"+Collections.list(e).size());
  • gunjan garg
    what is the difference in Enumeration and Iterator?if they are same then why we read these two different concepts
  • Lahar
    Enumeration is same as Iterator.
    and working of both are same but Main differnce is Iterator has remove().
    remove() removes the last object taken using next().
  • swetha
    Very Usefull and clear explanation
  • yonas
    v.hasNext() and v.hasMoreElements() are not equal to 1 operation, each.

    If you break it down to CPU cycles needed to run those functions, I guarantee you that they are AT LEAST as many CPU cycles as a for loop.

    Moreover, the compiler might simplify things like "int i = 0" to one operation.
  • Nevor
    Method calls are clearly not "1 operation" and furthermore you forget about the item.next() which is called at each loop. Thus, with a collection that has a O(1) get size, the for loop is more efficient than the iterator.
  • Nevor
    and a O(1) random access
  • rgz
    I just figured out that we can do this for exactly the same cost and the intention read a bit more clearly.

    for(Enumeration e = foos.getEnumeration(); e.hasMoreElements(); Foo foo = e.nextElement()){
    // process foo
    }
blog comments powered by Disqus