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. }
C.
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.