Java Reference
In-Depth Information
// Error: the object returned is of the Date type, not a
// String object.
String date
=
(String) list.lastElement ();
Yo u can use the operator
instanceof
to query the object for what type of object
it is:
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 of a particular object in the vector, as in
int i = list.indexOf ("Yet another string");
A
Vector
can also return an
Enumeration
.An
Enumeration
provides for
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, which is explained
in Section 10.9.)
Enumeration e = list.elements ();
while (e.hasMoreElements ()) {
System.out.println (e.nextElement ().toString ());
}
After
hasMoreElements()
returns
false
, the
Enumeration
cannot be used
again.
With the Java 1.2 Collections Framework (see Section 10.6) came a pre-
ferred alternative to
Enumeration
called
Iterator
. The
Iterator
class
differs from
Enumeration
in that the iterator permits removing one or more
elements from the
Vector
without damaging the
Iterator
.Inaddition,
the iterator methods
hasNext()
and
next()
have more concise names than
the corresponding methods
hasMoreElements()
and
nextElement()
in
Enumeration
.Weexplain more about the
Iterator
interface in Section 10.6.
10.4
Hashtable
,
Properties
, and
HashMap
The
Hashtable
class provides associative arrays with key-value pairings. Pre-
sentation of the key retrieves the value. The keys and values must be objects,
not primitive type values. If you want to include numerical values, then use the
corresponding wrapper classes such as
Integer
for an
int
value (or rely on
the autoboxing support in J2SE 5.0 as explained in Chapter 3).
Search WWH ::
Custom Search