|
Here's an example of how one could use an instance of class Vector,
and the interface Enumeration.
This code will run under all versions of the Java SDK.
package examples;
import java.util.Enumeration;
import java.util.Vector;
public class VectorExample
{
public static void main(String[] args)
{
Vector vector = new Vector();
vector.add("Mary");
vector.add("Frank");
vector.add("Joe");
vector.add("Sylvia");
vector.add("Vanessa");
for (int i = 0; i < vector.size(); i++)
{
String name = (String) vector.elementAt(i); // Note required cast
System.out.println(i + ": " + name);
}
for (Enumeration en = vector.elements(); en.hasMoreElements(); )
{
String name = (String) en.nextElement(); // Note required cast
System.out.println(name);
}
}
}
|
which outputs the following:
0: Mary
1: Frank
2: Joe
3: Sylvia
4: Vanessa
Mary
Frank
Joe
Sylvia
Vanessa
Note the two ways of obtaining the elements of the vector:
- Access each element by its index, using the elementAt(int index)
method
- Access each element through an Enumeration object, supplied by the
Vector. (Remember, Enumeration
is an interface.)
This works, but is considered "old style". So what's
the "new style"?
To learn about that, you'll have to
learn some more background...
|