Java Reference
In-Depth Information
return 1;
if (thisTotal < pTotal) {
return -1;
// must be equal
return 0;
The contract that the compareTo method guarantees (as described in its documentation) is that it will
return a positive number if the local object is greater than the object in the argument, a negative number
if the local object is less than the object in the argument, and 0 if the two are equal. It's also important
that, given the same object as an argument, the equals method returns true and the compareTo method
returns 0. To do that, just use the same fields in both methods. If you need to break the rule, be sure to
document it in the Javadoc for the compareTo method.
Tip A common problem is to try to cast a class that implements java.lang.Comparable to a class of your
own. Because they are in different packages (your class is in your own package and the other class is in the
java.lang.Comparable package), you can't cast your class to the other class. Integer is probably the class that
most often causes this problem, but any class that extends java.lang.Comparable has the same issue. So, if you
see a ClassCastException , remember this particular problem, because it is a likely cause of the exception.
Remember that to compare Person objects, you need to create another class with a main method,
set up a few Person objects, and then compare them. I include a class to do just that at the end of the
chapter, but why not give it a try now? As with so many other things, you can't learn to program unless
you program.
Implementing java.util.Comparator Although the Java community uses java.lang.Comparable for
natural comparisons, we implement a Comparator when we want to compare objects in some arbitrary
way. Also, because Comparator objects are themselves classes, it's possible to implement many different
Comparator objects for the same class. Let's expand our Person object to have a field by which we
probably wouldn't usually want to sort and then create a Comparator class to sort by it. That kind of thing
happens pretty often, really, because it allows for grouping by not-so-obvious characteristics. Listing 4-
31 shows the modified Person class.
Listing 4-31. Person class with a favorite topic field
package com.apress.javaforabsolutebeginners .examples.comparing;
public class Person implements Comparable<Person> {
String firstName;
String lastName;
String favoriteBook;
public Person (String firstName, String lastName, String favoriteBook) {
this.firstName = firstName;
Search WWH ::

Custom Search