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(); (This is the right answer) f. None of the above
Does this kind of question appear in the real exam? I ask this question because I think this question is more like a mathematical question rather than a programming one. [ January 12, 2004: Message edited by: Yosi Hendarsjah ]
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>
Joined: Oct 02, 2003
Anyway, I think your mock exam teaches a lot more than just what people need to pass the exam.