public int compareTo(Object another) throws CustomMadeException
{
if(this.getClass() != another.getClass() )
{
throw new CustomMadeException();
}
Car other = (Car) another;
return this.getBrand().compareTo(other.getBrand());
}
I don't understand what's wrong exactly with my code. Why can't it implement T in comparable? Do I have to change the argument of compareTo to T? But shouldn't it be Object? As far as I know, the implementation of compareTo in the interface comparable is blank.
The canonical way to do this is as follows:
public class Car implements Comparable<Car> {
...
public int compareTo(Car other)
{
return this.getBrand().compareTo(other.getBrand());
}
}
Note that your implementation of compareTo()
can't throw any checked exceptions, since none are permitted by the Comparable<T>.compareTo()
's throws
specification.