My app may compare instances of any two sub-classes of the same abstract parent class. I want them compared as follows:
The classes will be compared by a TreeMap, so I have a choice of using a Comparator, or implementing Comparable (or both?).
I can think of several ways to do this, but they are all a bit messy and error-prone. Is there an elegant solution?
Thanks in advance...
You could try
// 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
}
Similarly for other derived classes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With