When to use
Enumeration and when to use Iterator
Anyone tell me when to use Enumeration and when to use Iterator? Use Iterator always.
Well, apart from being an advantage this also is said to decrease performance by a tad. However, that's negligible. (Some amount of processing is involved in checking for modifications). If you see the docs it says about "well defined semantics" for the iterator, the fail-safe property adds to that. -- Vinay Binny Enumeration and Iterator are interfaces
in java.util package.
-- Bava All of the above are correct but we have forgotten about one thing - iterator is a design pattern and the purpose is to abstract looping. For example you have a class that loops thru Lists or ArraysLists so you used Enumeration. But suddenly another programmer made an Array (say String[]) that can only do for loop. Your enumeration is screwed I would say. So the strategy is to use Iterator. Now first you will have this method in your class: //this is Loop.java
So you use it this way:
Now this part is to show you haw to make an iterator out of a String[] 1. Make an Iterator Class public class CustomIterator implements java.util.Iterator{ String[] arry;
public CustomIterator(String[]
arry){
public boolean
hasNext(){
public Object
next(){
public void remove(){
and here is how you do it: Loop loop = new Loop();
String[] str = new String[]{"1","2","3","4","5"};
-- Steve Torrefranca Well, not really. What if I implement the iterator design pattern using the enumeration interface? The Iterator design pattern does'nt make it mandatory to implement a remove method. All it says is to give a iteration capability irrespective of the underlying collection. I'll make Custom Iterator implement Enumeration without the remove method. Now we've implemented the iterator design pattern using enumeration and the enumeration works fine. The eponymous iterator interface may have derived its name from the iterator pattern but does'nt mean that an Enumeration can use the iterator design pattern. -- Vinay Binny
Related:
Java Certification, Programming, JavaBean and Object Oriented Reference Books Return to : Java Programming Hints and Tips All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
|