An instance of the Vector
class provides a list of any Object
derived types. Vectors differ considrably from arrays. Arrays are
of only one type and the number of elements cannot be changed. Vectors
instead can hold a mix of class objects (they are, of course, all
subclasses of Object.)
Vectors can also grow and shrink:
Vector
list = new Vector ();
list.addElement (" a new string object");
list.addElement (" another new string object");
list.addElement (new Date ());
list.addElement (new Date ());
list.removeElementAt (3); // Remove the 3rd entry.
//
The current 4th entry then becomes the 3rd entry
When an element of a Vector
returns from a method, it is returned as an Object
type. So it must be cast to the proper type:
String
str = (String)list.firstElement ();
If you cast the returned object to a class that it
does not belong to, then an runtime ClassCastException
occurs:
String
date = (String)list.lastElement ();
** Error: the object returned is of the Date type, not
a String object. **
You can use the operator instanceof
to check for what kind of object has been returned.
Object
o = list.lastElement ();
if (o instanceof String)
String date = (String)o;
else if (o instanceof Date)
Date aDate = (Date)o;
The Vector
class has a number of other methods such as a search for the index
number
int
i = list.indexOf (str);
The class ArrayList
offers the same capabilities as Vector
but is not synchronized so a thread-safe (e.g. single thread) situation
for faster performance. See the Iterator
and ArrayList
section.
Enumeration
A Vector
can also return an Enumeration.
An Enumeration
provides a one time scan through a list of Objects. . (We note that
an Enumeration has no relationship at all with the enumerated
type of J2SE 5.0.)
Enumeration
e = list.elements ();
while (e.hasMoreElements ()) {
System.out.println(e.nextElement ().toString
());
}
After the hasMoreElements()
returns false,
the Enumeration
cannot be used again.
With Java 1.2 came an alternative to Enumeration
called Iterator.
We will discuss Iterator
after we discuss the Collections Framework.
References and Web Resources
Latest update: Nov. 18, 2004
|