import java.util.*; // The class we define for "Person" objects: class Person implements Comparable { // Some data: String firstName; String lastName; int birthYear; // We'll use this to decide what kind of sorting we want. public boolean sortByAge = false; // This is called a constructor: public Person (String firstName, String lastName, int birthYear) { this.firstName = firstName; this.lastName = lastName; this.birthYear = birthYear; } // To allow for printing via System.out.println: public String toString () { return "Person: " + firstName + " " + lastName + " (b. " + birthYear + ")"; } // A comparison method to allow two Person instances to be compared. public int compareTo (Person d) { // Check if object passed in is of correct type. if (! (d instanceof Person) ) { return -1; } // Cast to a Person variable so that we can access fields. Person p = (Person) d; if (sortByAge) { // Compare ages. if (birthYear < p.birthYear) { return -1; } else if (birthYear > p.birthYear) { return 1; } else { return 0; } } else { // Sort alphabetically by name, starting with lastname. if ( lastName.compareTo (p.lastName) < 0 ) { return -1; } else if ( lastName.compareTo (p.lastName) > 0 ) { return 1; } // If last names are equal, try first names. if ( firstName.compareTo (p.firstName) < 0 ) { return -1; } else if ( firstName.compareTo (p.firstName) > 0 ) { return 1; } else { return 0; } } } } //end-Person public class ObjectSortExample4 { public static void main (String[] argv) { Person[] someKennedys = new Person [10]; Person p = new Person ("Patrick", "Kennedy", 1858); System.out.println ("First one: " + p); someKennedys[0] = p; // Do the others: someKennedys[1] = new Person ("Joseph", "Kennedy", 1888); someKennedys[2] = new Person ("Rose", "Fitzgerald", 1890); someKennedys[3] = new Person ("Joseph", "Kennedy", 1915); someKennedys[4] = new Person ("John", "Kennedy", 1917); someKennedys[5] = new Person ("Jacqueline", "Bouvier", 1929); someKennedys[6] = new Person ("Robert", "Kennedy", 1925); someKennedys[7] = new Person ("Edward", "Kennedy", 1932); someKennedys[8] = new Person ("Caroline", "Kennedy", 1957); someKennedys[9] = new Person ("Maria", "Shriver", 1955); System.out.println ("Unsorted: "); print (someKennedys); System.out.println ("Sorted: "); Arrays.sort (someKennedys); print (someKennedys); // We want to sort by age, so set that flag in all instances. for (int i=0; i