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

(singke) #1
ptg7068951

Storing Objects of the Same Class in Vectors

13: list.add(moreNames[i]);
14: }
15: Collections.sort(list);
16: for (String name : list) {
17: System.out.println(name);
18: }
19: }
20:
21: publicstaticvoidmain(String[] args) {
22: StringLister lister = newStringLister(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
toStringListerand 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
Collectionsclass:


Collections.sort(list);


This class, like Vector, belongs to the java.utilpackage. 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 alpha-
betical 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.


The output of the StringLister
program.
Free download pdf