Enumerations and Iterators
10 April 2007An Enumeration is used for iterating over a given collection, Usually of unknown size. Iterator also has the same purpose but Enumeration does not allow modification of the collection, Which can be achieved using Iterator.
Iterator’s “remove” method removes from the underlying collection the last element returned by the iterator. This method can be called only once per call to the Iterator’s “next” method.
Following code sample will help you understand how to “Enumeration” and “Iterator”.
import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; public class link { public static void main (String []str){ Enumeration enum_cities; Vector cities = new Vector(); cities.add("New York"); cities.add("Sydney"); cities.add("Frankfurt"); cities.add("Delhi"); cities.add("Milan"); cities.add("Paris"); enum_cities = cities.elements(); while (enum_cities.hasMoreElements()) System.out.println(" -Enum- " + enum_cities.nextElement()); Iterator it_cities = cities.iterator(); String str_temp= ""; System.out.println(" Actual size of vector: " + cities.size()); while (it_cities.hasNext()) { str_temp = it_cities.next().toString(); if(str_temp.equals("Sydney")) it_cities.remove(); else System.out.println(" -Iterator- " + str_temp); } // iterator removed Sydney from vector so its size is reduced to 5 System.out.println("Current size of vector: " + cities.size()); } } If you want to use enumeration with arrays, following code sample code: import java.lang.reflect.Array; import java.util.Enumeration; final public class ArrayFactory { static public Enumeration makeEnumeration(final Object obj) { Class type = obj.getClass(); if (!type.isArray()) { throw new IllegalArgumentException(obj.getClass().toString()); } else { return (new Enumeration() { int size = Array.getLength(obj); int cursor; public boolean hasMoreElements() { return (cursor < size); } public Object nextElement() { return Array.get(obj, cursor++); } }); } } public static void main(String args[]) { Enumeration e = makeEnumeration(new int[] { 1, 3, 4, 5 }); while (e.hasMoreElements()) { System.out.println(e.nextElement()); } } }
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Enumerations and Iterators
Thanks
It is very helpful
its great tip, it is simple and very clear about the concepts..