programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Paul Clapham
• Ron McLeod
• Jeanne Boyarsky
• Tim Cooke
Sheriffs:
• Liutauras Vilda
• paul wheaton
• Henry Wong
Saloon Keepers:
• Tim Moores
• Tim Holloway
• Stephan van Hulst
• Carey Brown
• Frits Walraven
Bartenders:
• Piet Souris
• Himai Minh

# what is the most appropriate hash code implementation

Ranch Hand
Posts: 32
• • Number of slices to send:
Optional 'thank-you' note:
• • I have copy pasted the code from the WHIZLABS scjp 1.4 simulator

given the above class what are the correct implementations of hashCode() method..?

[A] return 0;

[B] return a;

[C] return a+b;

[D] return a-b;

[E] return a ^ b;

[F] return (a<<16)|b;

here I think the answer is
A,B,C,E

but suprisingly the answer provided by WHIZLABS simulator is A,C,E

please correct me if I am wrong

Ranch Hand
Posts: 78
• • Number of slices to send:
Optional 'thank-you' note:
• • The rule about the equals and hashCode implementations is the following :
( a.equals(b) ) implies ( a.hashCode() == b.hashCode() ).

In this example, B is not a correct answer because using only "a" as hashCode
value doesn't fullfil the condition above if the two ValuePair instances are
equals because (VP1.a == VP2.b) && (VP1.b == VP2.a). VP1.a and VP2.a can be
different in that case, and the rule would be broken.

Hope it helps.

Gilles

Ranch Hand
Posts: 32
• • Number of slices to send:
Optional 'thank-you' note:
• • got it.Thanks a lot Gilles.I hv worked it out using this sample objects

(1,2)(1,3)(3,4)(2,1)

here as per equals method objects (1,2) and (2,1) are treated as equal objects but both are placed into different buckets with numbers 1 and 2 respectively.Since equal objects must be placed in same buckets this is a contradictions.

using your explanation I visualized like this.

Ranch Hand
Posts: 201
• • Number of slices to send:
Optional 'thank-you' note:
• • Can you explain how C is correct answer??

Greenhorn
Posts: 15
• • Number of slices to send:
Optional 'thank-you' note:
• • C is correct.

For eg. object 1 (a,b) is (2,5)
object 2 is (2,5)
obj1 and obj2 are equal as per our definition

Hashcode a+b = 7 for both objects. so both objects are placed in same bucket.

if obj2 is (5,2), then also they are equal as per our definition.
here also hashcode is a+b= 7 for both objects and hence placed in same bucket.

For a-b this will not be true. Hence a-b is false Self destruct mode activated. Instructions for deactivation encoded in this tiny ad. Free, earth friendly heat - from the CodeRanch trailboss https://www.kickstarter.com/projects/paulwheaton/free-heat