Java OCA OCP Practice Question 3233

Question

Given the following class, which statements are correct implementations of the hashCode() method?.

class Main {//from ww  w .ja  v a2s  .co  m
  public int a, b;
  public boolean equals(Object other) {
    try {
      Main o = (Main) other;
      return (a == o.a && b == o.b)
          || (a == o.b && b == o.a);
    } catch (ClassCastException cce) {
      return false;
    }
  }
  public int hashCode() {
    // (1) INSERT CODE HERE.
  }
}

Select the three correct answers.

  • (a) return 0;
  • (b) return a;
  • (c) return a + b;
  • (d) return a - b;
  • (e) return a ^ b;


(a), (c), and (e)

Note

The equals() method ignores the ordering of a and b when determining if two objects are equivalent.

The hashCode() implementation must, therefore, also ignore the ordering of a and b when calculating the hash value, i.e., the implementation must return the same value even after the values of a and b are swapped.




PreviousNext

Related