Tuesday 8 April 2014

Java Enumeration and Iterators

Enumeration
An enumeration is an object that generates elements one at a time. It is 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:


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

Iterators have three 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:


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


 

No comments:

Post a Comment