Reputation: 13
I wanted to ask why we use the comparable interface in java? Wouldn't it be simpler to just make the compareTo method without using the comparable interface?
Instead of doing this:
//some class that implements comparable
public int compareTo(someClass someInstanceOfThatClass) {
// do stuff that returns -1,0,or 1
}
Why can't we just do this:
//some class that does NOT implement comparable, but we still
//make a compareTo method
public int compareTo(someClass someInstanceOfThatClass) {
// do stuff that returns -1,0, or 1
}
I guess my question is why do we bother implementing comparable, if we could just make a compareTo method without being forced to by some interface (comparable)?
Upvotes: 1
Views: 306
Reputation: 1655
I think it returns to the innate concept of the interface. You always sure that every class which has implemented Comparable interface, has ability to be compared and sometimes you need this assurance. For example if you have a method that have a parameter with Comparable type, then you are sure that comapreTo is implemented with that parameter and this parameter issemantically comparable. But whitout interface you can't get this assurance.
Upvotes: 0
Reputation: 51034
Java's type system is nominal, not structural, so simply having the method required by the interface is not enough to implement it; you also have to declare that the class implements the interface. In some other languages such as Typescript, having the method with the right signature would be enough, but Java is not like that.
If you are only calling the compareTo
method from your own code then this may not matter, but if you are using classes or methods from the standard library or from other libraries which take Comparable
things as arguments, then your class will need to implement the interface so you can pass your objects to them.
Upvotes: 2
Reputation: 72844
Comparable
is an interface, hence it imposes a contract that others may follow. For example, calling Collections.sort(list)
only works if the elements are instances of Comparable
, and internally relies on the compareTo
method to implement the sorting.
Upvotes: 3