Search code examples
javainterfacecomparable

Why use compareTo() from Comparable Interface when overriding the compareTo() method?


I have been googling around and the closest response (not answer) is here, but I am confused of the response. I am trying to sort some dog names using Collection.sort(), so I need to learn to use Comparable interface. My questions:

1) why do I need to use the compareTo() that came from the interface when I "override" the compareTo()?
2) If the compareTo() from Comparable interface is a default method, why doesn't it has a "default" keyword in front of the method? Java SE 8 Menu

Here is the partial code:

Collections.sort(list);   
for(Dog a: list)   // printing the sorted list of names
     System.out.print(a.getDogName() + ", ");

Here is the class implement the Comparable interface:

class Dog implements Comparator<Dog>, Comparable<Dog> {
   private String name;
   private int age;

   Dog() {}

   Dog(String n, int a) {
      name = n;  age = a;
   }

   public String getDogName() {
      return name;
   }

   public int getDogAge() {
      return age;
   }

   public int compareTo(Dog d) {
      return (this.name).compareTo(d.name);  //###.....my question
   }

   // Override Comparator Interface's compare() to sort "ages"
   public int compare(Dog d, Dog d1) {
      return d.age - d1.age;
   }
}

Solution

  • Here's something to think about.

    A Dog is Comparable to other Dogs. It is not itself something that compares two other Dogs.

    So, implementing Comparable is "more correct".

    And you are conflicting two methods.

    static <T extends Comparable<? super T>> void sort(List<T> list)

    Sorts the specified list into ascending order, according to the natural ordering of its elements.

    So, Collections.sort(dogs); will sort your list.

    static <T> void sort(List<T> list, Comparator<? super T> c)

    Sorts the specified list according to the order induced by the specified comparator.

    This is how you use that method.

    Collections.sort(dogs, new Comparator<Dog>() {
        @Override
        public int compare(Dog d1, Dog d2) {
            return d1.compareTo(d2); // Call the Comparable method
        }
    )};
    

    You can, of course, implement that inner method to order by age

    return Integer.compare(d1.getAge(), d2.getAge());