File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashCode method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hashCode method" Watch "hashCode method" New topic
Author

hashCode method

Yosi Hendarsjah
Ranch Hand

Joined: Oct 02, 2003
Posts: 164
From Dan's mock:

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 ]
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
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>
Yosi Hendarsjah
Ranch Hand

Joined: Oct 02, 2003
Posts: 164
Anyway, I think your mock exam teaches a lot more than just what people need to pass the exam.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashCode method