Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Storing Objects of the Same Class in Vectors 161

The name of the class held by the vector is placed within charac-
ters, as in this statement:


Vector victor = new Vector();


The preceding statement creates a vector that holds strings. Identifying a
vector’s class in this manner utilizes generics, a way to indicate the kind of
objects a data structure like vector holds. If you are using vectors with an
older version of Java, you’d write a constructor like this:


Vector victor = new Vector();


Although you can still do this, generics make your code more reliable
because they give the compiler a way to prevent you from misusing a vec-
tor. If you attempt to put an Integerobject in a vector that’s supposed to
hold Stringobjects, the compiler fails with an error.


Unlike arrays, vectors aren’t created with a fixed number of elements they
hold. The vector is created with 10 elements. If you know you’re storing a
lot more objects than that, you can specify a size as an argument to the
constructor. Here’s a statement that creates a 300-element vector:


Vector victoria = new Vector(300);


You can add an object to a vector by calling its add()method, using the
object as the only argument:


victoria.add(“Vance”);
victoria.add(“Vernon”);
victoria.add(“Velma”);


You add objects in order, so if these are the first three objects added to
victoria, element 0 is “Vance”, element 1 is “Vernon”, and element 2 is
“Velma”.


You retrieve elements from vectors by calling their get()method with the
element’s index number as the argument:


String name = victoria.get(1);


This statement stores “Vernon” in the namestring.


To see if a vector contains an object in one of its elements, call its
contains()method with that object as an argument:


if (victoria.contains(“Velma”)) {
System.out.println(“Velma found”);
}

Free download pdf