There is a question on the K&B CD that I suspect has an incorrect solution...
The question 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 fill the equals() and hashCode() contracts for this class?
A. return((SortOf)o).bal == this.bal;
B. return((SortOf)o).code.length() == this.code.length();
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 selected C (which is correct) but the solution mentions that D is also correct. As far as I can tell D should NOT be correct since there are values of code.length(), bal and rate such that equal SortOf's could have different hashCodes!
for example, if one SortOf has code="blah" (length=4), bal=2 and rate=3, and another SortOf has code="da" (length=2), bal=3 and rate= 4, then the SortOf's are equal() but they have different hashCodes which violates the contract.