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 hashcode contract S&B question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "hashcode contract S&B question" Watch "hashcode contract S&B question" New topic
Author

hashcode contract S&B question

Martin Sergeant
Greenhorn

Joined: May 20, 2003
Posts: 24
This question is taken from the Sierra and Bates mock exam that comes with the SCJP 1.6 book

Given:-

Which of the following when inserted will fufill equals and hascode conrtacts 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 think the answer d is incorrect if you consider the following scenario

object 1 has code.length =2, bal=3 and rate=4
object 2 has code.length =4, bal=2 and rate=3

in this case their hashcodes will be different 2*3 != 4*2
but equals will return true 2*3*4 == 4*2*3
which breaks the hashcode equals contract

Therefore c is the only correct answer

Is this right or am I missing something?

Martin
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

You are correct


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Jeevan Reddy
Ranch Hand

Joined: Nov 10, 2009
Posts: 142
Wouter Oet wrote:You are correct


Does it mean, only fields used in evaluating hashCode should be used in equals method?
Please clarify.

SCJP 1.6 (94%)
http://faq.javaranch.com/java/JspFaq
Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9189
    
    2

janardhan nanduri wrote:Does it mean, only fields used in evaluating hashCode should be used in equals method?

Not necessarily. You just need to make sure that the hashCode and equals contract is fulfilled that's all. Example


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Simran Dass
Ranch Hand

Joined: Jan 09, 2010
Posts: 183

You are right Martin . Only option C is correct.
I had also faced problem in the same question . I had chosen only option C.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: hashcode contract S&B question
 
Similar Threads
Wrong Answer in Master Exam? [equals() and hashCode() Contract]
mistake in k&b hashCode()/equals() contract question
hashcode & equals question
A question from Mock Test about hashCode
HashCode and Equals