aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hashcode contract Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Hashcode contract" Watch "Hashcode contract" New topic
Author

Hashcode contract

Shivani Chandna
Ranch Hand

Joined: Sep 18, 2004
Posts: 380
In the below question:


If inserted at the specified location, which of the following statements would produce the most efficient hashCode method?



a. return 31;
b. return getI1();
c. return getI2();
d. return getI1() + getI2();
e. return 31 * getI1() + getI2();

Answer is e : But the explanation states "All of the statements would produce a hashCode method that is consistent with the hash code contract"

Given that equals () method uses both int i1 and i2 should not hashCode() use both variables? And if hashCode() uses just one variable - would not that break the contract?

Thanks !!!


/** Code speaks louder than words */
Richard Green
Ranch Hand

Joined: Aug 25, 2005
Posts: 536
Lets say i1=3 and i2=4

Hashcode ==> (getI1()+getI2()) is not effective as it would give u the same result when i1=4 and i2=3 (or) i1=1 and i2=6

whereas 31 * getI1() + getI2()is more effective as it would give different results for (i1=3, i2=4) & (i1=4,i2=3) * (i1=1,i2=6)

Hope this helps


MCSD, SCJP, SCWCD, SCBCD, SCJD (in progress - URLybird 1.2.1)
Santana Iyer
Ranch Hand

Joined: Jun 13, 2005
Posts: 335
hashCode is infact using both variables while computing hashCode(),
it just multiplies first variable i1 with prime number.

thus produces efficient hashCode, a is also legal but inefficient
while b, c, d are illegal.
Balazs Borbely
Ranch Hand

Joined: Oct 11, 2004
Posts: 33
Originally posted by Santana Iyer:
hashCode is infact using both variables while computing hashCode(),
it just multiplies first variable i1 with prime number.

thus produces efficient hashCode, a is also legal but inefficient
while b, c, d are illegal.


I my opinion also ALL answers respect the hashCode contract and e is the most efficent. So e is the correct answer.

In your opinion, what part of the contract isn't satisfied for b,c,d?


'Make everything as simple as possible, but not simpler.' --Albert Einstein
Shivani Chandna
Ranch Hand

Joined: Sep 18, 2004
Posts: 380
Originally posted by Santana Iyer:
while b, c, d are illegal.


Exactly thats what I asked b,c,d options are incorrect hashcode implementations ?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hashcode contract