Sunday, August 8, 2010

equals() and hashCode()

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

Which statements are true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden? (Choose all that apply.) 

  1. If the equals() method returns true, the hashCode() comparison == might return false

    This is a negation of the equals() and hashCode() contract. If equals() method returns true, hashCode() method MUST return true.


  2. If the equals() method returns false, the hashCode() comparison == might return true

    Correct. Two dissimilar objects can return the same hashcode value


  3. If the hashCode() comparison == returns true, the equals() method must return true

    Incorrect because the hashCode() method is very flexible in its return values, and often two dissimilar objects can return the same hash code value. 

  4. If the hashCode() comparison == returns true, the equals() method might return true

    Correct because if the hashCode() comparison returns ==, the two objects might or might not be equal.


  5. If the hashCode() comparison != returns true, the equals() method might return true
          This is a negation of the equals() and hashCode() contract. If  
     equals() method returns true, hashCode() method MUST return true.

No comments:

Post a Comment