Modifying Enumeration Data Sources

Modifying Enumeration Data Sources

Since the java.util.Enumeration class provides read-only access to the element list it represents, it may intuitively seem that the list of elements is immutable, or cannot be changed. However, the Enumeration is often used as a way to reference data stored in some structure that can change, even while the Enumeration’s elements are being processed. This code creates a Vector, populates it with three elements, and then obtains an Enumeration, which represents the list of elements.

 import java.util.*;public class VecTest {	public static void main(String[] args) {		Vector v = new Vector();		v.addElement("First");		v.addElement("Second");		v.addElement("Third");		Enumeration e = v.elements();		while (e.hasMoreElements()) {			System.out.println(e.nextElement());			if (v.size() > 0) v.removeElementAt(0);		}  //  while (e.hasMoreElements())	}  //  public static void main()}  //  public class VecTest

While you might expect the Enumeration to return three elements, it only returns two, because after the first one is displayed, it is removed from the Vector, causing the Enumeration to skip over the second one. As a result, the output from running this code is:


To avoid this type of behavior, you should either ensure that the Enumeration’s data source will not change, or create a copy (perhaps using the clone() method) of the source and obtain the Enumeration object from that copy.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist