Java Reference
In-Depth Information
this.firstName = firstName;
this.surname = surname;
}
public String toString() {
return firstName + " " + surname;
}
// Compare Person objects
public int compareTo(Object person) {
int result = surname.compareTo(((Person)person).surname);
return result == 0 ? firstName.compareTo(((Person)person).firstName):result;
}
private String firstName; // First name of person
private String surname; // Second name of person
}
We use the compareTo() method for String objects to compare the surnames, and if they are equal
the result is determined from the first names. We can't apply the sort() method from the
Collections class to a Crowd object though - a Crowd is not a list since it doesn't implement the
List interface. A Vector does though, so we can sort the people member of the Crowd class by
adding a sort() method to the class:
class Crowd {
// Sort the people
public void sort() {
Collections.sort(people); // Use the static sort method
}
// Rest of the class as before...
}
We can just pass our Vector object to the sort() method, and this will use the compareTo()
method in the Person class to compare members of the list.
Let's see if it works for real.
Try It Out - Sorting the Stars
You can now add a statement to the main() method in TryVector , to sort the cast members:
public static void main(String[] args) {
Person aPerson; // A person object
Crowd filmCast = new Crowd();
// Populate the cast
for( ; ; ) { // Indefinite loop
aPerson = readPerson(); // Read in a film star
if(aPerson == null) // If null obtained...
Search WWH ::




Custom Search