Java Reference
In-Depth Information
Listing 17-34.
A Test Class to Test the ComparablePerson Class and the Comparable Interface
// ComparablePersonTest.java
package com.jdojo.interfaces;
import java.util.Arrays;
public class ComparablePersonTest {
public static void main(String[] args) {
ComparablePerson[] persons = new ComparablePerson[] {
new ComparablePerson("John", "Jacobs"),
new ComparablePerson("Jeff", "Jacobs"),
new ComparablePerson("Wally", "Inman")};
System.out.println("Before sorting...");
print(persons);
// Sort the persons list
Arrays.sort(persons);
System.out.println("\nAfter sorting...");
print(persons);
}
public static void print(ComparablePerson[] persons) {
for(ComparablePerson person: persons){
System.out.println(person);
}
}
}
Before sorting...
Jacobs, John
Jacobs, Jeff
Inman, Wally
After sorting...
Inman, Wally
Jacobs, Jeff
Jacobs, John
Using the Comparator Interface
The
Comparable
interface imposes a specified ordering on objects of a class. Sometimes you may want to specify
a different ordering for objects of the class from the ordering specified in the class by the
Comparable
interface.
Sometimes you may want to specify a particular ordering for the objects of a class that does not implement the
Comparable
interface. For example, you may want to specify ordering on objects of the
ComparablePerson
class
based on the first name and the last name, as opposed to the ordering specified by its
compareTo()
method of the
Comparable
interface, which is the last name and the first name. The
Comparator
interface lets you specify a custom