I read that :
whenever a collection need to be sorted, the elements must be mutually comparable.
I wrote the below code and it
In order for classes A
and B
to be mutually comparable, these requirements need to be satisfied:
compareTo
on an instance of A
passing an instance of B
must be allowedcompareTo
on an instance of B
passing an instance of A
must be alloweda.compareTo(b)
returns x
, then b.compareTo(a)
must return a value y
with the opposite sign, or zero, when x
is zero.The classes in your code are not mutually comparable, because an attempt to pass an instance of c
to b
's compareTo
(and vice versa) works fine. However, they are not comparable to instances of their own classes, which would create a problem if you were to add more items to the collection to be sorted.
In order for the container to be sortable, your class needs to be comparable to instances of its own type as well.