Consider the following Person
class:
public class Person {
private String name, // Guaranteed never
comment; // to be null
private int ageInYears;
// Other methods omitted for brevity
@Override public boolean equals(Object o) {
if (o instanceof Person) {
final Person p = (Person) o;
return ageInYears == p.ageInYears &&
name.equals(p.name);
} else {
return false;
}
}
@Override public int hashCode() {
return ageInYears + 13 * comment.hashCode();
}
}
We assume the above equals()
implementation to be correct. Answer the following two
questions:
-
Is this implementation correct regarding the contract
between equals() and
hashCode() ? Correct if
necessary.
-
After correcting possible flaws: Is the resulting
implementation »good« with respect to distinguishing objects?
Amend if possible.
Explain your answers.
|