Java OCA OCP Practice Question 1488

Question

How many of the following pairs of values can fill in the blanks to comply with the contract of the hashCode() and equals() methods?

class MyClass { 
   public int hashCode() { 
      return ___; 
   } 
   public boolean equals(Object o) { 
      return ___; 
   } 
} 
  • I. 1, false
  • II. 1, true
  • III. new Random().nextInt(), false
  • IV. new Random().nextInt(), true
  • A. None
  • B. One
  • C. Two
  • D. Three


A.

Note

An object is required to have the same value for repeated calls to hashCode() if the value has not changed.

This makes III and IV incorrect.

If two objects are equal, they are required to have the same hash code.

Since equality must be reflexive, it cannot return false if the same object is passed, and I is incorrect.

Since equals() must return false when null is passed in, it cannot be true and II is incorrect.

Option A is the answer.




PreviousNext

Related