wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About equals() and hashcode() contracts Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About equals() and hashcode() contracts" Watch "About equals() and hashcode() contracts" New topic
Author

About equals() and hashcode() contracts

L Yan
Greenhorn

Joined: Apr 25, 2006
Posts: 18
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: About equals() and hashcode() contracts