Java Reference
In-Depth Information
Arrays
- includes tools for handling arrays such as fast filling, searching and sorting
BitSet
- manipulation of bits
Note that in Chapter 8 we already examined the
Timer
and
TimerTask
classes,
also from
java.util
.InChapter 4 we discussed the
java.util.Random
class for generating random numbers.
10.3
Vector
and
Enumeration
An instance of the
Vector
class provides a list of objects. The elements of a
Vector
are references to
Object
types, which, of course, include all objects in
Java. A
Vector
differs considerably from an
Object
array in that it can grow
and shrink whereas the number of elements in an array cannot be changed from
the array size initially created.
Forexample, we can create a
Vector
and add different objects to it and then
remove an element from the middle:
Vector list = new Vector ();
list.addElement ("A string");
list.addElement ("Another string");
list.addElement ("Yet another string ");
list.addElement (new Date ());
list.addElement (new Date ());
list.removeElementAt (3);
...
There are several methods that provide access to the entries in a
Vector
. These
include:
Object get (int index)
Object firstElement ()
Object lastElement ()
Object [] toArray ()
The
get()
method returns the element at the specified index. The next two
methods listed return the first and last elements in the
Vector
. The last method
shown dynamically builds and returns an array of references to the objects in the
Vector
.
Note that these methods return as
Object
type references. To treat the ref-
erence as any type other than
Object
,you must cast it to its proper class or
superclass. For example, if you know that you've put a
String
object into the
Vector
, then you first retrieve the
Object
and then cast it to a
String
:
String str
=
(String) list.firstElement ();
If you cast the returned object to a class that it does not belong to, then a runtime
ClassCastException
occurs:
Search WWH ::
Custom Search