I got this question from Practice exam of Kathy Sierra book CD.
Q-52
clss Sortof{
String name;
int bal;
String code;
short rate;
public int hashCode() {
return (code.length() * bal);
}
public boolean equals(Object o) {
// insert code
}
}
Which of the following would fulfill the equals() and hashCode() contracts of the class?
A & B irrelevant
C. return ((SortOf)o).code.length() * ((SortOf)o).bal == this.code.length()* this.bal;
D. return ((SortOf)o).code.length() * ((SortOf)o).bal * ((SortOf)o).rate== this.code.length()* this.bal * this.rate;
The answer given is C & D.
but in D, isn't it possible for the hashcode to be not equal, and cause equals() to return true? Isn't that a violation of the contract?
eg:-
Sortof1 - code.length() = 2
bal =3
rate = 4
Sortof2 - code.length() = 3
bal = 4
rate = 2