ptg7068951
HOUR 12:Making the Most of Existing Objects
Yo u c a n re m o v e a n o b j e c t f ro m a v e c t o r u s i n g i t s e l f o r a n i n d e x n u m b e r :
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 specialforloop 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 forloops 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 victoriavector, displaying each name
to the screen:
for (String name : victoria) {
System.out.println(name);
}
The hour’s first project takes vectors and the special forloop 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: importjava.util.*;
2:
3: publicclassStringLister {
4: String[] names = { “Spanky”, “Alfalfa”, “Buckwheat”, “Daria”,
5: “Stymie”, “Marianne”, “Scotty”, “Tommy”, “Chubby” };
6:
7: publicStringLister(String[] moreNames) {
8: Vector
9: for (int i = 0; i < names.length; i++) {
10: list.add(names[i]);
11: }
12: for (int i = 0; i < moreNames.length; i++) {