我的应用程序可以比较同一抽象父类的任意两个子类的实例。我希望将它们进行如下比较:
- 如果是不同的子类,则由父类进行比较。
- 如果是相同的子类,则由子类进行比较。
这些类将通过 TreeMap 进行比较,因此我可以选择使用 Comparator,或实现 Comparable(或两者兼而有之?)。
我可以想到几种方法来做到这一点,但它们都有点困惑并且容易出错。有优雅的解决方案吗?
提前致谢...
最佳答案
你可以试试
// Parent:
@Override
public final int compareTo(Parent other)
{
if (getClass() == other.getClasss()) {
// same type -> pass it to subclass implementation
return this.subCompare(other)
}
// different type -> do the comparison here based on Parent's logic
// ...
}
protected int subCompare(Parent other)
{
// this should not be called directly
return 0; // could throw an exception here too
}
// Derived1:
@Override
protected int subCompare(Parent other)
{
// this method is only called from Parent
Derived1 other1 = (Derived1) other;
// do the comparison based on Derived1's logic
}
其他派生类也类似
关于java - 比较 Java 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10725007/