Java Reference
In-Depth Information
You can implement the
Comparable<>
interface very easily for your
Person
class, as follows:
public class Person implements Comparable<Person> {
// Constructor
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
}
@Override
public String toString() {
return firstName + " " + surname;
}
// Compare Person objects
public int compareTo(Person person) {
int result = surname.compareTo(person.surname);
return result == 0 ? firstName.compareTo(person.firstName) : result;
}
private String firstName; // First name of person
private String surname; // Second name of person
}
Directory "TryVector"
You use the
compareTo()
method in the
String
class to compare the surnames, and if the surnames are
equal, the result is determined from the first names.
You can just pass your
Vector<Person>
object to the
sort()
method, and this uses 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 statements to the
main()
method in
TryVector
to sort the cast members:
public static void main(String[] args) {
// Code as previously...
// Now sort the vector contents and list it
Collections.sort(filmCast);
System.out.println("\nThe cast in ascending sequence is:\n");