posted 20 years ago
Yosi,
Yes, the real exam does ask questions about efficient hashCode method implementations.
a. return 31;
b. return getI1();
c. return getI2();
d. return getI1() + getI2();
e. return 31 * getI1() + getI2(); (This is the right answer)
f. None of the above
A hashCode method that returns the constant value 31 is consistent with the hash code contract. Even so, a hashCode method that returns the same value regardless of the internal state of the object is not very good, because it will cause hashtables to place every instance of the class in the same bucket. The expression 31 * getI1() + getI2() produces the most efficient hashCode method, because it is most likely to produce unique hashcodes for various combinations of i1 and i2. The expression getI1 is less efficient, because it does not use all of the values that are used by the equals method. The expression getI1() + getI2() is less efficient, because it produces the same hash code when the values of i1 and i2 are swapped.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>