Storing Objects of the Same Class in Vectors

An important decision to make when writing a computer program is where to store data. In the first half of this tutorial, you've found three useful places to keep information: basic data types like int and char, arrays, and String objects. Any Java class can hold data. One of the most useful is Vector, a data structure that holds objects of the same class. Vectors are like arrays, which also hold elements of related data, but they can grow or shrink in size at any time. The Vector class belongs to the java.util package of classes, one of the most useful in the Java 2 class library. An import statement makes it available in your program:

import java.util.Vector;


A vector holds objects that either belong to the same class or share the same superclass. They are created by referencing two classes—the Vector class and the class the vector will hold. The name of the class held by the vector is placed within "<" and ">" characters, as in this statement:

Vector<String> victor = new Vector<String>();


The preceding statement creates a vector that will hold strings. Identifying a vector's class in this manner utilizes generics, an enhancement of Java 2 version 5. If you were using vectors with an older version of Java, you would 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 vector. If you attempted to put an Integer object in a vector that's supposed to hold String objects, the compiler fails with an error. Unlike arrays, vectors aren't created with a fixed number of elements they hold. The vector will be created with 10 elements. If you know you're storing a lot more objects than that, a size can be specified as an argument to the constructor. Here's a statement that creates a 300-element vector:

Vector<String> victoria = new Vector<String>(300);


An object can be added to a vector by calling its add() method, using the object as the only argument:

victoria.add("Vance");
victoria.add("Vernon");
victoria.add("Velma");


Objects are added in order, so if these were the first three objects added to victoria, element 0 is "Vance", element 1 is "Vernon", and element 2 is "Velma". Elements are retrieved 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 name string. To see whether a vector contains an object in one of its elements, call its contains() method with that object as argument:

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


An object can be removed from a vector using itself or an index number:

victoria.remove(0);
victoria.remove("Vernon");


These two statements leave "Velma" as the only string in the vector.

Looping Through a Vector

Java 2 version 5 introduces a new for loop that makes it easy to load a vector and examine each of its elements in turn. This loop has two parts, one less than the for loops you learned about in Hour 8, "Repeating an Action with Loops." The first part is the initialization section: the class and name of a variable that holds each object retrieved from the vector. This object should belong to the same class that holds the vector. The second part identifies the vector. Here's code that loops through the victoria vector, displaying each name to the screen:

for (String name : victoria) {
 System.out.println(name);
}


Watch Out!

As a new feature of Java 2 version 5, this for loop won't work in previous versions of the language. You'll encounter an error if you attempt to compile the code examples from this section with a development tool that isn't current.


The hour's next project takes vectors and the new for loop for a spin, presenting a list of strings in alphabetical order. The list comes from an array and command-line arguments. Enter the text of Listing 12.1 into your text editor, saving the file as StringLister.java.

Listing 12.1. The Full Text of StringLister.java
 1: import java.util.*;
 2:
 3: public class StringLister {
 4: String[] names = { "Spanky", "Alfalfa", "Buckwheat", "Daria",
 5: "Stymie", "Marianne", "Scotty", "Tommy", "Chubby" };
 6:
 7: public StringLister(String[] moreNames) {
 8: Vector<String> list = new Vector<String>();
 9: for (int i = 0; i < names.length; i++) {
10: list.add(names[i]);
11: }
12: for (int i = 0; i < moreNames.length; i++) {
13: list.add(moreNames[i]);
14: }
15: Collections.sort(list);
16: for (String name : list) {
17: System.out.println(name);
18: }
19: }
20:
21: public static void main(String[] arguments) {
22: StringLister lister = new StringLister(arguments);
23: }
24: }


Compile the StringLister app, a program that displays strings in alphabetical order. When you run the app, specify one or more names as command-line arguments, as in this command:

java StringLister Jackie Mickey Farina Woim


The names specified at the command line are added to the names stored in an array in Lines 4–5. Because the total number of names is not known until the program runs, a vector serves as a better storage place for these strings than an array. The vector's strings are sorted in alphabetical order using a method of the Collections class:

Collections.sort(list);


This class, like Vector, belongs to the java.util package. Vectors and other useful data structures are called collections in Java. Example output for the StringLister app follows:

Alfalfa Buckwheat Chubby Daria Farina Jackie Marianne Mickey Scotty Spanky Stymie Tommy Woim


      
Comments