2015-01-29 3 views
-1

같은 인터페이스를 공유하는 모든 클래스의 클래스를 가질 수있는 비교자를 만들고 싶습니다. 그러나 다음 코드는 작동하지 않습니다.Comparator를 같은 인터페이스의 클래스와 연결하는 방법은 무엇입니까?

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 { 

} 

무엇이 잘못 되었나요? 어떻게이 비교를 할 수 있습니까?

+1

'ComparatorChain' 클래스의 코드를 공유 할 수 있습니까? –

+0

저는 여기서 ComparatorChain이 필요하다고 생각하지 않습니다. ComparatorChain은 비교기 목록에서 각 비교기가 0이 아닌 값을 반환 할 때까지 실행합니다. – BretC

+0

또는이 지원 기능이 내장 된 Java 8을 사용할 수 있습니다. –

답변

2

예상됩니다. ComparatorChain<TestInterface>TestInterface을 구현하는 모든 클래스의 인스턴스를 비교할 수있는 비교자를 허용합니다. TestClassA의 인스턴스 만 비교할 수있는 비교자를 체인에 추가하려고합니다. 그래서 체인이이 콤퍼레이터를 받아들이면 TestClassA 인스턴스 이외의 다른 요소를 비교할 때 유형이 안전하지 않을 수 있습니다. 당신이 TestClassA의 비교기와 경우에도 TestClassATestClassB주 공통 인터페이스를 TestClassB의 인스턴스를 비교할 수 없기 때문에 당신이 원하는 무엇

, 단순히 불가능합니다.

+0

확인합니다. 아마도 'Comparator'가 표시됩니다. 내 유스 케이스에 부적합한 ... – membersound

관련 문제