Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 4 ■ OPERATORS


Listing 4-32. Book comparator class

package com.apress.javaforabsolutebeginners .examples.comparing;

import java.util.Comparator;

public class BookComparator implements Comparator<Person> {

public int compare(Person p1, Person p2) {
return p1.favoriteBook.compareTo(p2.favoriteBook);
}
}

In this case, all we have to do is use the String class's compareTo method. Note that we must tell the
comparator what kind of thing to compare (with Comparator<Person>). Otherwise, we have to accept
arguments of type Object and cast to objects of type Person.

■ Note You don't need comparators for arrays of primitives or for collections of any objects that implement
java.lang.Comparable (such as String and Integer). Those objects are already comparable.

Finally, Listing 4-33 shows CompareTest, expanded to use both kinds of comparison.

Listing 4-33. CompareTest using both comparisons

package com.apress.javaforabsolutebeginners .examples.comparing;

import java.util.ArrayList;
import java.util.Collections;

public class CompareTest {

public static void main(String[] args) {
Person samSpade = new Person("Sam", "Spade", "The Maltese Falcon");
Person sherlockHolmes =
new Person("Sherlock", "Holmes", "The Sign of the Four");
Person johnWatson = new Person("John", "Watson", "A Study in Scarlet");
Person drWatson = new Person("John", "Watson", "A Study in Scarlet");
// compare the two that are really equal
System.out.println(johnWatson == drWatson);
System.out.println(johnWatson.equals(drWatson));
System.out.println();
System.out.println("Sorting by name");
// Make a collection from our characters and sort them
ArrayList<Person> characters = new ArrayList<Person>();
characters.add(samSpade);
characters.add(sherlockHolmes);
characters.add(johnWatson);
Free download pdf