The enumeration and iteration Functions List all elements in a set object in sequence, which are defined by the enumeration interface and the iterator interface respectively. The enumeration interface is defined in java standard 1.0, while the iterator interface is defined from java standard 1.2. The two have similarities and differences. However, we recommend that you use the iterator interface to replace the enumeration interface in Java.
The following describes the differences between the two:
The enumeration Interface contains only two method declarations, which are described as follows:
① Public
Boolean hasmoreelements ()
② Public object
Nextelement ()
In actual use, the nextelement () method is used to list the elements of a set in sequence. Currently
The enumeration interface only exists in the previous collection class vector and hashtable (so it is rarely used), as shown below:
Enumeration Method in Java. util. hashtable:
① Public
Enumeration elements () // obtain an enumeration of all values in the hashtable object
② Public Enumeration
Keys () // obtain an enumeration of all keys in the hashtable object
Enumeration Method in Java. util. Vector:
① Public Enumeration
Elements () // obtain an enumeration of all elements in a vector object
The sample code is as follows:
Public class demo
{
Public
Static void main (string [] ARGs)
{
Vector v = new
Vector ();
V. Add ("F ");
V. Add ("B ");
V. Add ("C ");
V. Add ("D ");
V. Add ("Z ");
V. Add ("");
Enumeration
E = V. Elements ();
While
(E. hasmoreelements ())
{
System. Out. Print (E. nextelement () +"
");
}
}
}
The iterator interface provides all functions of the enumeration interface.
Provides a remove () method. The detailed description is as follows:
Boolean
Hasnext ()
Object next ()
Void remove ()
The sample code is as follows:
Public class
Demo
{
Public static void main (string [] ARGs)
{
List
List = new
Arraylist ();
List. Add ("ABC ");
List. Add ("EFG ");
List. Add ("hij ");
List. Add ("KlM ");
Iterator
It = List. iterator ();
While (it. hasnext ())
{
System. Out. Print (it. Next () +"
");
}
}
}