Veg
Veg

Reputation: 636

Extending a java comparator to compare a specific class implementing the interface it compares for

I have a comparator like this:

public class XComparator implements Comparator<X>, Serializable {
}

that is currently used to sort a list of Y objects where Y implements X

I want to create a comparator for Y that extends XComparator so that i can compare based on a boolean data member of Y and then called super.compare.

I've tried several different approaches to this, but none seem to work at all. Is this even possible?

Upvotes: 4

Views: 11020

Answers (2)

Aaron Kurtzhals
Aaron Kurtzhals

Reputation: 2036

Use delegation instead of inheritance.

Your YComparator should contain and delegate to an XComparator.

Upvotes: 0

matts
matts

Reputation: 6897

It is not possible to extend XComparator and change the generic parameter on Comparator to Y, but you could create a YComparator class which just has an XComparator internally and delegates to it. Something like:

public class YComparator implements Comparator<Y>, Serializable {
    private XComparator xComparator = new XComparator();

    @Override
    public int compare(Y y1, Y y2) {
         // compare y1.booleanData with y2.booleanData
         if (...)
             ...;

         // else otherwise:
         return xComparator.compare(y1, y2);
    }
}

Upvotes: 11

Related Questions