Java OCA OCP Practice Question 107

Question

Given the following class:

class MyClass { 
     int a, b; 

     public boolean equals(Object x) { 
       MyClass that = (MyClass)x; 
       return this.a == that.a; 
     } 
}

Which methods below honor the hash code contract?

A.  public int hashCode() { return a; } 

B.  public int hashCode() { return b; } 

C.  public int hashCode() { 
          return a+b; 
    } /*from ww  w.j a v a  2  s .com*/

D.  public int hashCode() { 
          return a*b; 
    } 

E.  public int hashCode() { 
          return (int)Math.random(); 
    } 


A, E.

Note

The hash code contract states that if two objects are equal, they must have equal hash codes.

In this case two objects are equal if their a values are equal.

If two such objects have different b values, then answers B, C, and D will return unequal hash codes for equal objects, which violates the contract.

E always returns 0; it's strange and inefficient, but it doesn't violate the contract.




PreviousNext

Related