Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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:
 
First
Third
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.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date