Java Reference
In-Depth Information
second can be any object. Thus, you have complete control over the list of
objects in instance d .
To reference an element of Vector d , use instance function get , giving it as
argument the number of the desired object. The following example writes the
first two elements of d on the Java console, separated by a comma and a blank:
System.out.println(get(0) + ", " + get(1));
Suppose we want to store d[1] of Vector d in a fresh String variable s
(given d as in Fig. 5.3). The following statement does not work:
String s= d.get(1); // Illegal statement
We state here how to fix it, without explanation. Thereafter, for those who
already know about class Object and casting, we explain why it does not work.
To retrieve and use an element using function get , you generally have to
know what class that element is and cast it to that class. In the above case, d[1]
is class String . So, the expression to obtain object d[1] is (String) d.get(1) ,
and this should be stored in s:
String s= (String) d.get(1);
The class of elements in a Vector
This little subsection should be read only if you know about the class hier-
archy, class Object , and casting.
The elements of a Vector automatically have class Object , the superest
class of them all. Therefore, when retrieving an element, you have to:
Cast an object that is retrieved from an instance of Vector to the
subclass to which it belongs so that the instance methods of the
subclass can be used.
Suppose d contains the name of the object in Fig. 5.3. Then, the first and second
elements of d can be retrieved and stored using these two statements:
Integer i= (Integer) d.elementAt(0);
String s= (String) d.elementAt(1);
Each element is cast from class Object down to the subclass that it really is.
Of course, if you do not know the class of a particular element, you must
find out, using operation instanceof , before casting it. If you attempt to cast it
to a class that it is not, a ClassCastException will be thrown, and your program
will (probably) abort.
The safe thing to do is to make all the elements in a Vector have the same
class-type, but of course this is not always appropriate.
Search WWH ::

Custom Search