Enumeration interface
The enumeration interface itself is not a data structure. However, it is important for other data structures. The enumeration interface defines the means by which continuous data is obtained from a data structure. For example, enumeration defines a method named Nextelement that can be used to get the next element from a data structure that contains multiple elements.
The enumeration interface provides a standard set of methods, since enumeration is an interface whose role is limited to providing method protocols for data structures. Here is an example of use:
E is a object that implements the enumeration interface
while (E.hasmoreelements ()) {
Object o= e.nextelement ();
System.out.println (o);
}
The object that implements the interface consists of a series of elements that can be called continuously to get the elements in the enumeration enumeration object. Nextelement (). Only the following two methods are defined in the Enumertion interface.
Boolean hasmoreelemerts ()
Tests whether the enumeration enumeration object also contains elements, and if true, indicates that there are at least one element.
· Object nextelement ()
If the Bnumeration enumeration object also contains elements, the method obtains the next element in the object.
Cases
/*
* @ (#) Demoenumeration.java
* Demonstrates the use of the enumeration interface
* /
Import java.util.*;
Class demoenumeration{
public static void Main (string[] args) {
Instantiating an object of type Mydatastruct
Mydatastruct mysatastruct=new mydatastruct ();
Gets the enumeration object that describes the Mydatastruct type Object
Enumeration Myenumeration =mydatastruct.getenum ();
Use an object loop to display each element in an object of type Mydatastruct
while (Myenumeration.hasmoreelements ())
System.out.println (Myenumeration.nextelement ());
}
}
Myenumeration class implements enumeration interface
Class Myenumerator implements Enumeration
{
int count; Counter
int length; The length of the stored array
Object[] DataArray; Storing a reference to an array of data
Constructors
myenumeration (int count,int length,object[] dataarray) {
This.count = count;
This.length= length;
This.dataarray=dataarray;
}
public boolean hasmoreelements () {
Return (count< length);
}
Public Object nextelement () {
return dataarray[count++];
}
}
The Mydatastruct class is used to instantiate a simple, enumeration object that can be supplied
To the data result object used by the program
Class Mydatasttuct
{
string[] data;
Constructors
Mydatastruct () {
Data=new String[4]
Data[0] = "zero";
Data[1]= "one";
DATA[2] = "both";
Data[3]= "three";
}
Returns a enumeration object to the user program
Enumeration Getenum () {
return new Myenumeration (0,data.length,data);
}
The running result of the program is:
Zero
One
Both
Three
Brief Introduction to Java Enumeration (go)