Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

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
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?

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

Joined: Aug 03, 2008
Posts: 9258

8

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://aspose.com/file-tools

subject: hashcode contract S&B question