Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Java subclasses

Tags:

java

My app may compare instances of any two sub-classes of the same abstract parent class. I want them compared as follows:

  1. If they are different sub-classes, the parent class should do the comparison.
  2. If they are the same sub-class, the sub-class should do the comparison.

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...

like image 384
Barry Fruitman Avatar asked May 02 '26 11:05

Barry Fruitman


1 Answers

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

like image 111
Attila Avatar answered May 05 '26 02:05

Attila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!