CHAPTER 4 ■ OPERATORS
Implementing java.lang.Comparable
Another best practice acknowledged by the Java community is to use java.lang.Comparable for
comparisons that are “natural” to the object. People naturally sort themselves by name (just look at a
phone book), so it makes sense to implement java.lang.Comparable and have its compareTo method tell
us whether a name is less than, equal to, or greater than another person's name. Listing 4-30 shows our
Person class again, with the addition of implementing java.lang.Comparable. For our Person example,
we get the numeric value of each String field, add them together, and use that as the numeric value of
our Person object.
Listing 4-30. Person class implementing java.lang.Comparable
package com.apress.javaforabsolutebeginners .examples.comparing;
public class Person implements Comparable
String firstName;
String lastName;
public Person (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public boolean equals(Person p) {
if (p == null) {
return false;
}
if (p == this) {
return true;
}
if (!(p instanceof Person)) {
return false;
}
if (p.lastName.equals(this.lastName)
&& p.firstName.equals(this.firstName)) {
return true;
} else {
return false;
}
}
public int hashCode() {
int result = 17;
result = firstName.hashCode() 37;
result = lastName.hashCode() 37;
return result;
}
public int compareTo(Person p) {
int thisTotal = firstName.hashCode() + lastName.hashCode();
int pTotal = p.firstName.hashCode() + p.lastName.hashCode();
if (thisTotal > pTotal) {