File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About equals and hashCode contract Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "About equals and hashCode contract" Watch "About equals and hashCode contract" New topic
Author

About equals and hashCode contract

Helen Ma
Ranch Hand

Joined: Nov 01, 2011
Posts: 319
I was doing a quiz from the exam simulator from Kathy and Bert's study guide, here is the quiz:
public 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
}
}

Two of the Choices:

c . ((SortOf)o).length()* ((SortOf)o) == this.code.length() * this.bal

d . ((SortOf)o).code.length()* ((SortOf)o).bal * ((SortOf)o).rate== this.code.length()* this.bal * this.rate


I think choice d is not right in my opinion. Let's say o has 5,3,1 for code length, bal and rate and this instance has 1, 3,5 correspondingly.
When two SortOf objects are equals based on choice d, their hash codes should be the same. However, the hash codes are 15 and 3 based on hashCode() method.
Therefore, when we are asked which choice satisfy the equal and hashcode contract, c is the only choice. However, the suggested solution is c and d.

Can anyone explain to me why d is the answer?
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 2686
Helen Ma wrote:Can anyone explain to me why d is the answer?

That's a popular question this week.


Joanne
 
 
subject: About equals and hashCode contract
 
Threads others viewed
Wrong Answer in Master Exam? [equals() and hashCode() Contract]
Doubt-MasterExam-Hashcode
HashCode and Equals
mistake in k&b hashCode()/equals() contract question
A question from Mock Test about hashCode
IntelliJ Java IDE