The issue is that whenever you want a collection to be sorted, its elements must be mutually comparable. Remember that unless otherwise specified, objects of different types are not mutually comparable.
How can we specify objects of different types to be mutually comparable? If a Cat class implements Comparable<Dog>, and a Dog class implements Comparable<Cat> Can we say now that Dog and Cat are mutually comparable? I have tried the above but its not working and I am getting ClassCastException. Please explain!
The ClassCastException is being thrown only for the second Dog object. If your try to add another Cat Object also, the same exception will be thrown. Because, when we observe the sequence,
1) empty set 2) first Cat is added; This is assumed to be the smallest in sorting order. 3) then Dog is added; which can compare the already existing Cat object in the set since it has signature compare(Cat c). This compares it and places it appropriately. In our case, assume it is larger and kept second in sorting order. 4) then second Dog is added. This again can compare itself with Cat. So, it will proceed with comparison with the Dog object already in set. Here since it has only compare(Cat), this expects the other object to be a Cat but it is a Dog. Thats why the exception occurs.
So, you cannot have a Dog class that compares itself with a Cat class.
But still you can achieve this (not recommended though), using no generic types. Keep simple Comparable. Use instanceof inside the compare() method.