Saw this in a book:
Given:
class SortOf {
String name;
int bal;
String code;
short rate;
public int hashCode() {
return (code.length() * bal);
}
}
does the following:
public boolean equals(Object o) {
return ((SortOf)o).code.length() * ((SortOf)o).bal * ((SortOf)o).rate == this.code.length() * this.bal * this.rate;
}
satisfy the equals contract?
Suppose
SortOf Ahascode = "AA"; bal=2; rate=2andSortOf Bhascode = "A"; bal=4; rate=2;Then for
A,code.length = 2,bal = 2,rate = 2andBhascode.length = 1,bal = 4,rate=2. ThenA.equals(B)butA.hashCode() != B.hashCode()Apart from your other issues with the code, I believe this violates the contract.
Edited to add: Actually, it may be that this definition of
equals()technically satisfies the contract forObject.equals(), which makes no demand on consistency withhashCode(). It’s the contract forObject.hashCode()whose contract demands consistency withequals(). What’s that about small minds and foolish consistency…? <andersoj leaves to apply to law school>This
equals()is reflexive, symmetric, transitive, consistent. I guess it violates the contract because.equals(null)throws an exception rather than returningfalseas required. All theequals()spec says abouthashCode()is: