Java OCA OCP Practice Question 599

Question

What happens when you try to compile and run this application?

 1. import java.util.*; 
 2. //w w w.  j  a v  a 2 s.c o  m
 3. public class MyClass { 
 4.   public static void main(String[] a) { 
 5.     Set<MyClass> set = new TreeSet<MyClass>(); 
 6.     set.add(new MyClass()); 
 7.     set.add(new MyClass()); 
 8.     set.add(new MyClass()); 
 9.   } 
10. } 
  • A. Compiler error.
  • B. An exception is thrown at line 6.
  • C. An exception is thrown at line 7.
  • D. An exception is thrown at line 8.
  • E. No exception is thrown.


C.

Note

The MyClass class doesn't implement Comparable, so a tree set doesn't know how to handle it.

The problem appears when the second MyClass instance is added to the set, requiring the set to perform a comparison between its two members.

The add() method throws ClassCastException.




PreviousNext

Related