Java OCA OCP Practice Question 1228

Question

Given:

import java.util.TreeSet;

class MyClass {//from   ww  w. j  a  v  a 2 s.c om
   int size;

   MyClass(int s) {
      size = s;
   }
}

public class Main {
   public static void main(String[] args) {
      TreeSet<Integer> i = new TreeSet<Integer>();
      TreeSet<MyClass> d = new TreeSet<MyClass>();

      d.add(new MyClass(1));
      d.add(new MyClass(2));
      d.add(new MyClass(1));
      i.add(1);
      i.add(2);
      i.add(1);
      System.out.println(d.size() + " " + i.size());
   }
}

What is the result?

  • A. 1 2
  • B. 2 2
  • C. 2 3
  • D. 3 2
  • E. 3 3
  • F. Compilation fails
  • G. An exception is thrown at runtime


G is correct.

Note

Class MyClass needs to implement Comparable in order for a TreeSet to be able to contain MyClass objects.




PreviousNext

Related