Java OCA OCP Practice Question 2980

Question

Given:

class Square {//from w  w w .j a v a2 s  .  co m
   Square(String c, int h) {
      color = c;
      hotness = h;
   }

   String color;
   int hotness;

   public boolean equals(Object o) {
      Square c = (Square) o;
      if (this.color == c.color)
         return true;
      return false;
   }

   public int hashCode() {
      return (color.length() + hotness);
   }
}

If instances of class Square are to be used as keys in a Map, which are true? (Choose all that apply.)

  • A. The code will not compile.
  • B. The hashCode() and equals() contracts have been supported.
  • C. The equals() method is reflexive, symmetric, and transitive.
  • D. The Square class CANNOT be used to create keys to reliably add and retrieve entries in a Map.
  • E. If the hashCode() method is not considered, the equals() method could be an override that supports the equals() contract.
  • F. If the equals() method is not considered, the hashCode() method could be an override that supports the hashCode() contract.


C, D, E, and F are correct.

Note

Taken individually, the equals() and hashCode() methods are legal, potentially contract-fulfilling overrides.

The problem is that they don't match each other.

In other words, two objects that are equal according to equals(), do not necessarily return the same result from hashCode().




PreviousNext

Related