Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

mistake in k&b hashCode()/equals() contract question

 
Paul Lachance
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just search this forum for "SortOf" and you come up with: this topic, amongst several others.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic