Java OCA OCP Practice Question 3145

Question

Which code, when inserted at (1), will provide a correct implementation of the hashCode() method in the following program?

import java.util.*;
public class Main {
 int count;/*w  w w  .  ja  va  2s. co  m*/
 int accumulated;
 public Main() {}
 public void record(int v) {
   count++;
   accumulated += v;
 }
 public int average() {
   return accumulated/count;
 }
 public boolean equals(Object other) {
   if (this == other)
     return true;
   if (!(other instanceof Main))
     return false;
   Main o = (Main) other;
   if (count != 0 && o.count != 0)
     return average() == o.average();
   return count == o.count;
 }
 public int hashCode() {
   // (1) INSERT CODE HERE ...
 }
}

Select the two correct answers.

  • (a) return 31337;
  • (b) return accumulated / count;
  • (c) return (count << 16) ^ accumulated;
  • (d) return ~accumulated;
  • (e) return count == 0 ? 0 : average();


(a) and (e)

Note

(b) is not correct since it will throw an ArithmeticException when called on a newly created Main object.

(c) and (d) are not correct since they may return unequal hash values for two objects that are equal according to the equals() method.




PreviousNext

Related