Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Possible Wrong answer in k&b Master Exam

Jyoti B.Shah
Greenhorn
Posts: 17
Hi All,

Which of the following will fulfill the equals() and hashcode() contracts:

1) return ((SortOf)o).code.length()*((SortOf)o).bal==this.code.length()*this.bal;
2) return ((SortOf)o).code.length()*((SortOf)o).bal*((SortOf)o).rate==this.code.length()*this.bal*this.rate;

I believe correct answer is only 1), as for example if object 1 has {length=2,bal=30,rate=5} and object2 has {length=1,bal=5,rate=60}, they will be equal as per equals() but their hashcodes will be different which violates the contract.

Regards,
Jyoti

Ireneusz Kordal
Ranch Hand
Posts: 423
In your example objects' hascodes will be the same, but equlas() return false - this doesnt violate the hashcode contract.

Jyoti B.Shah
Greenhorn
Posts: 17
Hi Ireneusz,

I still do not under stand. In my example:

Object 1: has {length=2,bal=30,rate=5}

and

Object2 has {length=1,bal=5,rate=60}

hascode for Object 1 will be length*bal = 60

hashcode of Object 2 will be length*bal = 5

Hashcode values are different although equals return true(2*30*5==1*5*60)

Doesn't this voilates the contract? Am i missing something??

Have an exam tomorrow...any response on this is highly appreciated!

Nitish Bangera
Ranch Hand
Posts: 537
yeah the possible answer if you see in terms of equals contract is only the 1st one. Well in the real exam you will get how many choices you have to make apart from the k&b types of choose all that apply stuff. Also here as far as i understand, we have to look in terms if hashcode is equal then what....

I will be giving the exam on 21 and i think this type will surely come as choose best of the answers.

Ankit Garg
Sheriff
Posts: 9610
37
This has been discussed before too. And it was concluded that this is a mistake in the Master Exam...

Jyoti B.Shah
Greenhorn
Posts: 17
Thank you all for you replies. Sorry i didn't search the ranch before posting the message.