Win a copy of Functional Reactive Programming this week in the Other Languages forum!

Hashcode contract

Shivani Chandna
Ranch Hand
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 !!!

Richard Green
Ranch Hand
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

Santana Iyer
Ranch Hand
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
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?

Shivani Chandna
Ranch Hand
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 ?