Search code examples
javacomparablecompareto

Why is Java 'Comparable' better than just using a compareTo method?


  1. I see that Comparable interface allowed implementation of just the compareTo method. So why do we even need this interface? Why can't we simply define and declare the method in any class we want, without having to implement the Comparable interface?

  2. I understand that this is correct: SortedSet<String> exampleSet = new TreeSet<String>(); <-- TreeSet implements SortedSet interface. So if I have a class called "Date" that implements Comparable, is this correct: Comparable<Date> example = new Date<Date>();. If yes, what exactly do I get? I mean what kind of object do I get? What properties does it have? If not, why not?


Solution

  • Why can't we simply define and declare the method in any class we want, without having to implement the Comparable interface?

    How would you expect a sorting method to work in that case?

    It's really handy to be able to sort any collection where the elements are all comparable with each other - and an interface is the way to express that.

    is this correct: Comparable<Date> example = new Date<Date>();

    No, not unless Date itself were generic. You could write:

    Comparable<Date> example = new Date();
    

    ... but it would be odd to do so. Normally Comparable is used by code which wants to compare existing objects - so it would fetch values from a collection and compare them with each other, for example.