Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Home » Tip Bank » C++ » Coding
Language: Java
Expertise: Intermediate
May 17, 1999



Application Security Testing: An Integral Part of DevOps

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();
		Enumeration e = v.elements();
		while (e.hasMoreElements()) {
			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.
Brett Spell
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date