Extend the Java comparator to compare specific classes of interfaces that implement its comparison

I have a comparator like this:

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

Currently used to sort the list of Y objects that implement X

I want to create a comparator for Y to expand XComparator so that I can compare the Boolean data members of Y and call super.. compare.

I've tried several different methods, but none seems to work Is this even possible?

Solution

You cannot extend xcomparator and change the generic parameter on the comparator to y, but you can create a ycomparator class that has only one xcomparator internally and delegate to it It's 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);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>