Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 746
Veg Avatar asked Oct 17 '25 14:10

Veg


1 Answers

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);
    }
}
like image 179
matts Avatar answered Oct 20 '25 03:10

matts