Java OCA OCP Practice Question 1212

Question

Given:

3. import java.util.*;
4. class MyClass {
5.   int size;//from  ww w.j  a  v  a  2  s  .  c o  m
6.   public MyClass(int s) { size = s; }
7.   public boolean equals(Object o) { return (this.size == ((MyClass)o).size); }
8.   // insert code here
9. }
10. public class Main {
11.   public static void main(String[] args) {
12.     LinkedHashSet<MyClass> t = new LinkedHashSet<MyClass>();
13.     t.add(new MyClass(1));   t.add(new MyClass(2));   t.add(new MyClass(1));
14.     System.out.println(t.size());
15.   }
16. }

And these two fragments:

I.   public int hashCode() { return size/5; }
II.  // no hashCode method declared

If fragment I or II is inserted independently at line 8, which are true? (Choose all that apply.)

  • A. If fragment I is inserted, the output is 2
  • B. If fragment I is inserted, the output is 3
  • C. If fragment II is inserted, the output is 2
  • D. If fragment II is inserted, the output is 3
  • E. If fragment I is inserted, compilation fails
  • F. If fragment II is inserted, compilation fails


A and D are correct.

Note

While fragment II wouldn't fulfill the hashCode() contract (as you can see by the results), it is legal Java.

For the purpose of the exam, if you don't override hashCode(), every object will have a unique hash code.




PreviousNext

Related