Enumeration interface (enumeration)
The Java. util. Enumeration interface is similar to the iterator interface. However, it only provides the function to traverse elements in a set of vector and hashtable (and subclass perperties) types, and does not support element removal. In addition, the iterator interface adds an optional remove operation and uses a shorter method name.
Note: The functions of this interface are the same as those of the iterator interface. The iterator interface rather than the enumeration interface should be preferred for the new implementation.
Public enumeration elements (); // all elements in the vector are listed starting from index 0. This method returns an enumeration object.
Generally, the following two methods in enumeration are used to print all elements in the vector:
(1) Boolean hasmoreelements (); // whether there are any elements. If true is returned, at least one element is contained.
(2) Public object nextelement (); // If an enumeration object also contains elements, this method returns the next element of the object. If no, a nosuchelementexception exception is thrown.
Usage 1:
// VEC is the object of the vector (SET) Class implemented by the interface. Vec. Elements () gets an element of the vector (SET.
For (enumeration E = Vec. Elements (); E. hasmoreelements ();)
{System. Out. println (E. nextelement ());}
Usage 2:
// E is an object that implements the enumeration Interface
While (E. hasmoreelements ()){
Object o = E. nextelement ();
System. Out. println (O );
}
In this way, the object implementing the enumeration interface generates a series of elements and generates one at a time. That is, the object implementing this interface is composed of a series of elements. You can call the nextelement () method consecutively to obtain the elements in the enumeration object.
Example: testenumeration. Java
Import java. util .*;
Public class testenumeration {
Public static void main (string [] ARGs ){
Vector v = new vector ();
V. addelement ("Lisa ");
V. addelement ("Billy ");
V. addelement ("Mr Brown ");
Enumeration E = V. Elements ();
While (E. hasmoreelements ()){
String value = (string) E. nextelement ();
System. Out. Print (value );
}
}
}
Output result:
Lisabillymr Brown