2017-09-12 10 views
1

입니다. 현재 내 compareTo 방법은 다음과 같습니다compareTo와 내가 POJO이처럼 보이는이 이적

@Override 
public int compareTo(EfdisJournal other) { 
    int i = this.type.compareTo(other.type); 
    if (i != 0) 
     return i; 
    if (this.bookingDate != null && other.bookingDate != null) 
     i = this.bookingDate.compareTo(other.bookingDate); 
    if (i != 0) 
     return i; 
    if (this.journalId != null && other.journalId != null) 
     i = this.journalId.compareTo(other.journalId); 
    if (i != 0) 
     return i; 
    return this.account.compareTo(other.account); 
} 

나는이 compareTo 방법으로 정렬을 실행하면,이 java.lang.IllegalArgumentException: Comparison method violates its general contract 오류가 발생합니다. 나는 약간의 구글을했다. 그리고 나는 필드의 약간이 비교 위에서 null이기 때문에 그것이 일어난다라고 생각한다. 그러나이 문제를 어떻게 해결해야하는지, 또는 내가 왜 그런 오류가 나타나는 지 알지 못한다.

비교는 다음과 같이 작동합니다 : 3이 journalId에 의해 account에 의해 비교 마지막에 비교으로 1 일, 다음 bookingDate에 의해 비교, type으로 비교합니다. 모든 비교는 오름차순이어야합니다.

  • type
  • bookingDate
  • journalId
  • account 결코 널 (null의 경우도있다) null의 경우 null는

편집 :

슬프게도 나는이 메소드를 구현할 수 없어서 순서가 필요에 따라 이루어졌다. 저장 프로 시저가 결과 집합을 2 개 생성 했으므로 문제를 해결했습니다. 두 번째 결과 집합은 필요에 따라 순서가 지정되었으므로 수행해야하는 유일한 작업은 첫 번째 결과 집합 대신 두 번째 결과 집합을 사용하는 것이 었습니다.

+0

어떻게 널 필드를 기준으로 요소를 주문 하시겠습니까? – Pshemo

+0

'null'bookingDate가있는 것들이 null이 아닌 bookingDate가있는 _before_ 또는 _after_ 가지를 정렬하고 'compareTo'를 적절하게 작성해야하는지 결정해야합니다. (그리고 나서'journalId'도 마찬가지입니다.) 그러면 순서대로 합의 할 수 있습니다. – khelwood

+0

'bookingdate'가 null 인 경우,'journalId'에 의해 비교되고, 또한 thatsn이 NULL이면,'account'와 비교해야합니다. 결과가 어떻게 나타나는지 업데이트 드리겠습니다. – XtremeBaumer

답변

1

당신은 하나 인스턴스가 널 bookingDate이있는 경우에 대처해야하고, 다른 하나는 null 이외의 bookingDate 있습니다. null이있는 항목이 bookingDate인지 여부를 결정해야하며, 0 이외의 항목 (0,) 이전이나 이후에 정렬되어야하며 compareTo를 적절하게 작성해야합니다. (그런 다음 journalId도 있습니다.) 그러면 일관되게 정렬되는 주문을받을 수 있습니다. 예를 들어

:

@Override 
public int compareTo(EfdisJournal other) { 
    int i = this.type.compareTo(other.type); 
    if (i != 0) { 
     return i; 
    } 
    if ((this.bookingDate==null)^(other.bookingDate==null)) { 
     return (this.bookingDate==null ? -1 : 1); 
    } 
    if (this.bookingDate != null && other.bookingDate != null) { 
     i = this.bookingDate.compareTo(other.bookingDate); 
    } 
    if (i != 0) { 
     return i; 
    } 
    if ((this.journalId==null)^(other.journalId==null)) { 
     return (this.journalId==null ? -1 : 1); 
    } 
    if (this.journalId != null && other.journalId != null) { 
     i = this.journalId.compareTo(other.journalId); 
    } 
    if (i != 0) { 
     return i; 
    } 
    return this.account.compareTo(other.account); 
} 
+0

'^'이 무엇을 설명 할 수 있습니까? – XtremeBaumer

+0

'^'는 배타적이거나 또는 피연산자 중 하나가 참이고 다른 하나가 거짓이면 참을 반환합니다. – khelwood

+0

아 좋아요. 슬프게도 당신의 해결책은 내가 찾는 결과를 낳지 않습니다. 내가 게시 한 예제처럼 주문한 목록을 얻을 수 있습니까? – XtremeBaumer

1

bookingDate 및/또는 journalId이 1이고 다른 하나는 null이 아닌 상황을 무시하고 있습니다.