wrote:
> Hi,
> I am new to Java and I was wondering what's the difference between
> implementing the Comparable interface, and just adding a "int
> compareTo" method in the class? Essentially they're doing the same
> thing, right? Thanks.
If you don't declare your class as implementing Comparable, there
is no way for other code to know that you've implemented compareTo.
Any code that uses Comparable will either accept it as a method
parameter or cast to it:
void sort( Comparable[] c ) {
}
or
void sort( Object[] o ) {
Comparable[] c = (Comparable[]) o;
}
If you don't declare your class to implement Comparable, then you
won't be able to use either of those methods. In the first case
the compiler will stop you and in the second a ClassCastException
will be thrown at runtime.
Eric