in which situations we have to implement the Comparable interface?
When you want to be able to compare 2 objects and get a result of equal, less than, or greater than.
Implementing Comparable gives your objects a compareTo
method. If you add them to a sorted list then they will automatically be sorted based on what your compareTo
method returns.
It's pretty basic. I don't know what else there is to add.
When your class implement the Comparable interface, you have to implement the compareTo() method in a way that you can clearly tell where an instance of your class would go in an ordered list of such instances.
Implementing efficient sorting algorithms and ordered collections isn't trivial. Therefore you would do this when you want objects of a class to have natural ordering, so you can use the proven sorting and order-dependent algorithms and classes provided by Java instead of implementing your own, like having the contents of a TreeSet remain ordered after insertions/deletions, or using Collections.sort().