View RSS Feed

My Java Tips

Enumerations and Iterators

Rate this Entry
by , 11-08-2011 at 06:31 PM (697 Views)
An 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".



Java Code:
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:
Java 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());
		}

	}
}

Submit "Enumerations and Iterators" to Facebook Submit "Enumerations and Iterators" to Digg Submit "Enumerations and Iterators" to del.icio.us Submit "Enumerations and Iterators" to StumbleUpon Submit "Enumerations and Iterators" to Google

Comments