The Comparable Interface Recall that Strings are Comparable using

advertisement
The Comparable Interface
Recall that Strings are Comparable using the compareTo method:
int compareTo(String other) // returns a value < 0 if this is less than other
// returns a value = 0 if this is equal to other
// returns a value > 0 if this is greater than other
Example:
String a = "apple";
String b = "banana";
System.out.println(a.compareTo(b) < 0); // true
/***
* The following is an example of how to sort an array of strings.
* This works because the sort method of the Arrays class uses
* the compareTo string method
*/
import java.util.Arrays;
public class SortingStrings
{
public static void main(String[] args)
{
String animals[] = new String[4];
animals[0] = "chicken";
animals[1] = "kangaroo";
animals[2] = "wombat";
animals[3] = "bird";
System.out.println("\nBefore Sorting");
for (int i=0; i<4; i++) {
System.out.println("animal " + i + " : " + animals[i]);
}
Arrays.sort(animals); // wow! Java has a built in sorting function
System.out.println("\nAfter Sorting");
for (int i=0; i<4; i++) {
System.out.println("animal " + i + " : " + animals[i]);
}
}
}
/*** An array of any object can be sorted if it implements the Comparable interface ***/
public class Person implements Comparable {
private String firstName;
private String lastName;
private int age;
public Person(String first, String last, int ageOf) {
firstName = first;
lastName = last;
age = ageOf;
}
public String toString() {
return firstName + ", " + lastName + ", " + age;
}
}
public int compareTo(Object anotherPerson) {
return this.age - ((Person) anotherPerson).age;
}
Modify the Person method compareTo so that if two people are the same age they are sorted
by last name.
/*** array persons can be sorted because Person implements the Comparable interface. ***/
import java.util.Arrays;
public class SortingPeople {
public static void main(String[] args) {
Person[] persons = {
new Person("Art", "Vandelay", 56), new Person("Carl", "Farbman", 45),
new Person("Dr.", "VanNostrand", 48), new Person("Joe", "Divola", 50),
new Person("Izzy", "Mandelbaum", 75), new Person("Jackie", "Chiles", 49)};
System.out.println("--- Before Sorting ---");
for (int i=0; i<persons.length; i++)
System.out.println(persons[i]);
Arrays.sort(persons);
}
}
System.out.println("\n --- After Sorting ---");
for (int i=0; i<persons.length; i++)
System.out.println(persons[i]);
Download