Friday, September 17, 2010

Code to Understand Objective 6.2

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)

6.2 Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.

To override toString() method in a class:

Overriding equals()

Heartbeat: "The equals() method in class Object uses only the == operator for comparisons, so unless you override equals(), two objects are considered equal only if the two references refer to the same object."

Overriding hashCode()

Hashing retrieval is a two-step process.

   1. Find the right bucket (using hashCode())
   2. Search the bucket for the right element (using equals() ).

transient variables can really mess with your equals() and hashCode() implementations. Keep variables non-transient or, if they must be marked transient, don’t use them to determine hashcodes or equality.

No comments:

Post a Comment