Java OCP 11 Programmer II Study Guide
145 page
2: public class UseTreeSet {
3: static class Rabbit{ int id; }
4: public static void main(
String[] args) {
5: Set<Duck> ducks = new TreeSet<>();
6: ducks.add(new Duck("Puddles"));
7:
8: Set<Rabbit> rabbits = new TreeSet<>();
9: rabbits.add(new Rabbit()); // ClassCastException
10: } }
Line 6 is fine. Duck does implement Comparable. TreeSet is able to sort it into the proper position in the set. Line 9 is a problem. When TreeSet tries to sort it, Java discovers the fact that
Rabbit does not implement Comparable. Java throws an exception that looks like this:
Exception in
thread "main" java.lang.ClassCastException:
class Duck cannot be cast to class java.lang.Comparable
class
Duck cannot be cast to class java.lang.Comparable -----