This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About equals() and hashcode() contracts" Watch "About equals() and hashcode() contracts" New topic

About equals() and hashcode() contracts

L Yan

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.
It is sorta covered in the JavaRanch Style Guide.
subject: About equals() and hashcode() contracts
Similar Threads
K&B Master Exam Question 56
equals and hashCode
hashcode & equals question
contract for equals and hashcode
A question from Mock Test about hashCode