Java Reference
In-Depth Information
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;
}
}
Let's examine that
equals
method. I followed a standard recipe for implementing it. (The Java
community has best practices for many things, and we show them to you whenever they come up, as
here.) First, I check for null, just to make sure we have an object. Then I check to see whether it's the
same object, in which case they are certainly equal. Then we check to make sure that, if we do have an
object, it's a
Person
object. If not, the comparison is always false. But remember that other classes might
extend our
Person
class, so a
Student
object might be equal to our
Person
object. Because
Student
extends
Person
, this
equals
method works for both. However,
Student
might implement its own
equals
method to account for the school each student attends. Finally, I check all the relevant fields within the
class. If they are all equal, it must be the same person. Naturally, a real-world
Person
class probably
includes middle name, address fields, social security number, and possibly even ancestors and
descendants. Two fields will do for the sake of a demonstration, though. Now, let's rewrite
CompareTest
to use our new
Person
object (see Listing 4-29).
Listing 4-29. Checking people objects for equality
package com.apress.javaforabsolutebeginners .examples.comparing;
public class CompareTest {
public static void main(String[] args) {
Person samSpade = new Person("Sam", "Spade");
Person greatNoirDetective = new Person("Sam", "Spade");
System.out.println(samSpade == greatNoirDetective);
System.out.println(samSpade.equals(greatNoirDetective));
}
}
CompareTest
now prints “false” and then “true,” even though
samSpade
and
greatNoirDetective
are
different references to different
Person
objects. That's because our
equals
method isn't comparing
references but rather the relevant fields of the two objects.