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

About equals() and hashcode() contracts

 
L Yan
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from K&B mock exam.

class SortOf {
String name;
int bal;
String code;
short rate;
public int hashCode()
{
return (code.length()*bal);
}
public boolean equals(Object o)
{
return ((SortOf)o).code.length()*((SortOf)o).bal*((SortOf)o).rate == this.code.length()*this.bal*this.rate;
}
}

Why this equals() and hashCode() fulfills contracts? Since when equals() return true, ((SortOf)o).code.length()*((SortOf)o).bal*((SortOf)o).rate == this.code.length()*this.bal*this.rate, hashCode() would not be equal. In other words, when X1*Y1*Z1=X2*Y2*Z2, X1*Y1 might != X2*Y2.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic