Java OCA OCP Practice Question 1184

Question

Given:

import java.util.HashMap;
import java.util.Map;

public class Main {
   public static void main(String[] args) {
      Map<MyClass, String> m = new HashMap<MyClass, String>();
      MyClass t1 = new MyClass("Monday");
      MyClass t2 = new MyClass("Monday");
      MyClass t3 = new MyClass("Tuesday");
      m.put(t1, "doLaundry");
      m.put(t2, "payBills");
      m.put(t3, "cleanAttic");
      System.out.println(m.size());
   }/*www.ja  v  a  2 s.  com*/
}

class MyClass {
   String day;

   MyClass(String d) {
      day = d;
   }

   public boolean equals(Object o) {
      return ((MyClass) o).day.equals(this.day);
   }
   // public int hashCode() { return 9; }
}

Which is correct?

Choose all that apply.

  • A. As the code stands, it will not compile
  • B. As the code stands, the output will be 2
  • C. As the code stands, the output will be 3
  • D. If the hashCode() method is uncommented, the output will be 2
  • E. If the hashCode() method is uncommented, the output will be 3
  • F. If the hashCode() method is uncommented, the code will not compile


C and D are correct.

Note

If hashCode() is not overridden, then every entry will go into its own bucket, and the overridden equals() method will have no effect on determining equivalency.

If hashCode() is overridden, then the overridden equals() method will view t1 and t2 as duplicates.




PreviousNext

Related