Content #
Employee本身实现了Comparable<Employee>接口。现有Java代码如下:
class Manager extends Employee
{
public int compareTo(Employee other)
{
Manager otherManager = (Manager) other; // NO
. . .
}
. . .
}
为什么这种实现方法是错误的?应如何解决?
Java语言对Comparable接口的实现有如下规定:
The implementor must ensure
sgn(x.compareTo(y)) = -sgn(y.compareTo(x))
for all x and y . (This implies that x.compareTo(y) must throw an exception if y.compareTo(x) throws an exception.)
如果x为Employee,而y是Manager,x.compareTo(y)不会抛出异常,而 y.compareTo(x)则会抛出异常,从而违反了这条规定。
解决的方案有两种:
- 认定两个不同类的对象不能比较,直接抛出异常:
if (getClass() != other.getClass()) throw new ClassCastException();
- 在超类中将compareTo声明为final,为所有自身或子类的对象制订统一的比
较规则。如,以Employee中的rank字段作为比较的依据。