2016-07-25 72 views
1

我目前正在努力對Java進行排序。我收到錯誤消息「比較方法違反其總合同」。我也理解這個錯誤消息,但我(主要)使用類型爲Long的buildin compareTo-Method。所以我不知道,在這種情況下,排序方法仍然違反了合同。這裏是我的代碼:buildin compareTo:比較方法違反其總體合同

@Override 
public int compareTo(DataAge another) { 
    if(this == null || another == null) 
     return 0; 

    Long a = new Long(this.getAge()); 
    Long b = new Long(another.getAge()); 
    return a.compareTo(b); 
} 

這裏的錯誤:

Java exception occurred: 
java.lang.IllegalArgumentException: Comparison method violates its general contract! 

at java.util.ComparableTimSort.mergeLo(Unknown Source) 

at java.util.ComparableTimSort.mergeAt(Unknown Source) 

at java.util.ComparableTimSort.mergeCollapse(Unknown Source) 

at java.util.ComparableTimSort.sort(Unknown Source) 

at java.util.ComparableTimSort.sort(Unknown Source) 

at java.util.Arrays.sort(Unknown Source) 

at java.util.Collections.sort(Unknown Source) 

at dd.GMAAnalyzer.sortData(Analyzer.java:158) 
+0

注:'這== null'永遠是假的。 –

回答

5

假設null s的允許,你的方法的邏輯是不正確的,因爲null比較無所不能。這是錯誤的,因爲它將比較等於多個彼此不相等的事物,從而打破了傳遞性。

要解決這個問題,決定是否null S的關係進行排序提前或其他數字的後面,並添加一個單獨的null比較(this不能等於null,所以你不需要爲它的比較)。

if(another == null) 
    return 1; // If you want nulls in the back, return -1 
+0

謝謝,解決了這個問題 – Thorsten

1

Comparable的Javadoc:

Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

而且,你不需要創建Long實例:

return Long.compare(this.getAge(), another.getAge()); 
相關問題