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 book, you’ve found three useful places to keep information: basic data types such as 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 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 holds.

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 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 vector. If you attempt 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 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<String> victoria = new Vector<String>(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 name string.

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");
}

You can remove an object 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 includes a special 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);
}

The hour’s first project takes vectors and the special for loop for a spin, presenting a list of strings in alphabetical order. The list comes from an array and command-line arguments.

With your Java24 project open within NetBeans, choose File, New File, and then create a new Empty Java File named StringLister. Enter Listing 12.1 in the source editor and save the file.

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[] args) {
22:         StringLister lister = new StringLister(args);
23:     }
24: }


Before you run the. application (choose Run, Run File), you should use the Run, Set Project Configuration, Customize command to set the main class to StringLister and the argument to one or more names separated by spaces, such as 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.

When you run the program, the output should be a list of names in alphabetical order (see Figure 12.2). The flexible size of vectors enables your additional names to be added to the data structure and sorted along with the others.

Figure 12.2. The output of the StringLister program.

Image
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.183.186