I'm new here and this is my first post. I've just completed my Java OCA and now moving onto studying for the OCP. I have a question regarding Comparable interface.
I have this code snippet which explains how Comparable is implemented:
import java.util.*;
public class Duck implements Comparable<Duck> {
private String name;
public Duck(String name) {
this.name = name;
}
public String toString() { // use readable output
return name;
}
public int compareTo(Duck d) {
return name.compareTo(d.name); // call String's compareTo
}
public static void main(String[] args) {
List<Duck> ducks = new ArrayList<>();
ducks.add(new Duck("Quack"));
ducks.add(new Duck("Puddles"));
Collections.sort(ducks); // sort by name
System.out.println(ducks); // [Puddles, Quack]
}
}
I more or less understand what is goin on here but below this code snippet the author quotes that:
The Duck class implements the Comparable interface. Without implementing that interface, all we have is a method named compareTo(), but it wouldn't be a Comparable object.
My question is why would it not be comparable? Is this something to do with the fact that calling code such as the Collections.sort()
would internally use the Comparable type as a reference parameter to compare any object?
Thanks in advance for any help and I hope my question makes sense.