Hi, I am running into a question about equals and hashCode contracts: here it is
Given:
class SortOf {
String name;
int bal;
String code;
short rate;
public int hashCode() {
return (code.length() * bal);
}
public boolean equals(Object o) {
// insert code here
}
}
Which of the following will fulfill the equals() and hashCode() contracts for this class? (Choose all that apply.)
Correct Answer 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;
I have a question about the last choice D, say if the two objects A: code.length=10, bal=10, rate = 100 B: code.length=10, bal=100, rate = 10 then using the equals() method in D, we get A.equals(B) evaluating to true right? but the they get different hashCode because they have a different balance? is it I misunderstood the concept somewhere ? can someone clarify this for me?
Thanks
Yang