Calling the compareTo() method on an object explicitly is something you won’t do except perhaps during testing, as was done here. Where it really comes into play is when using collections. The following example program creates several Person objects, inserts them into a list, then sorts the list using the Collections.sort() method. The results of running this program are shown in figure 23-7.
Example 23.11: CollectionTestApp.java
1 import java.util.*; 2 3 public class CollectionTestApp { 4 public static void main(String[] args){ 5 List list = new ArrayList(); 6 7 list.add(new Person("Rick", "W", "Miller", 1963, 5, 6, Person.MALE)); 8 list.add(new Person("Debbie", "S", "Sears", 1986, 8, 3, Person.FEMALE)); 9 list.add(new Person("John", "L", "Thompson", 1978, 1, 4, Person.MALE)); 10 list.add(new Person("Riddic", "H", "Bean", 2001, 11, 15, Person.MALE)); 11 list.add(new Person("Gloria", "J", "Albright", 1922, 12, 2, Person.FEMALE)); 12 list.add(new Person("Zena", "P", "Warrior", 1968, 1, 26, Person.FEMALE)); 13 list.add(new Person("Shelly", "H", "Marshall", 1993, 7, 15, Person.FEMALE)); 14 list.add(new Person("Jessica", "A", "Simpson", 1912, 6, 3, Person.FEMALE)); 15 list.add(new Person("Peter", "R", "Rabbit", 1999, 4, 30, Person.MALE)); 16 list.add(new Person("Mohamad", "A", "Abbas", 1961, 5, 29, Person.MALE)); 17 list.add(new Person("Sapna", "P", "Gupta", 1988, 8, 11, Person.FEMALE)); 18 list.add(new Person("Marvin", "C", "Williams", 1945, 2, 18, Person.MALE)); 19 list.add(new Person("Kyle", "V", "Miller", 1954, 9, 13, Person.MALE)); 20 list.add(new Person("Joseph", "L", "Smith", 1963, 10, 23, Person.MALE)); 21 list.add(new Person("Nora", "G", "Jones", 1977, 11, 4, Person.FEMALE)); 22 list.add(new Person("Hedy", "E", "Lamarr", 1914, 2, 28, Person.FEMALE)); 23 24 for(Iterator i = list.iterator(); i.hasNext();){ 25 System.out.println(i.next().toString()); 26 } 27 28 Collections.sort(list); 29 30 System.out.println("--------------Sorted List--------------------"); 31 for(Iterator i = list.iterator(); i.hasNext();){ 32 System.out.println(i.next().toString()); 33 } 34 } 35 } // end CollectionTestApp
Figure 23-7: Results of Running Example 23.11
Referring to figure 23-7 — The Person.compareTo() method causes Person objects to be sorted alphabetically by their string values. And since the Person.toString() method builds the string starting with first name, it appears at first that this is how they are being sorted.