简体   繁体   中英

How to chain Comparators with classes of same interface?

I want to create a comparator that can take any comparator of classes sharing the same interface. But the following code does not work:

public class MainApp {
    public void test() {
        ComparatorChain<TestInterface> comp = new ComparatorChain<>();
        comp.addComparator(new TestAComparator());
        // ERROR: The method addComparator(Comparator<TestInterface>) in the type ComparatorChain<TestInterface> is not applicable for the arguments (MainApp.TestAComparator)
    }

    //more comparators for each class implementing TestInterface
    class TestAComparator implements Comparator<TestClassA> { //TestClassA implements TestInterface
        @Override
        public int compare(TestClassA o1, TestClassA o2) {
            return 0;
        }
    }
}

public interface TestInterface {

}

//more classes that implement this interface
public class TestClassA implements TestInterface {

}

What is wrong here? How can I achieve this comparison?

This is expected. A ComparatorChain<TestInterface> accepts comparators that are able to compare instances of any class implementing TestInterface . You're trying to add to the chain a comparator that is able to compare instances of TestClassA only. So if the chain accepted this comparator, it would fail when comparing anything other than TestClassA instances, which would break its type-safety.

What you want to do is simply impossible, because you can't compare instances of TestClassB with a comparator of TestClassA , even if TestClassA and TestClassB share a common interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM