2013-12-21 31 views
3

下面幾行:Java的排序拋出java.lang.IllegalArgumentException異常:比較法違反其總承包

ArrayList<ShowdownSingleValueVO> sortedValues = new ArrayList<>(); 
(...fill the array...) 
Collections.sort(sortedValues); 

返回以下異常:比較法違反其總承包!

我明白,當比較方法不正確實施,但是這個異常通常發生在我的情況,它的實施是相當明顯的:

public static class ShowdownSingleValueVO implements Comparable<ShowdownSingleValueVO>{ 
    int hashValue; 
    byte showdownValue; 
    public ShowdownSingleValueVO(int hashValue, byte showdownValue) { 
     this.hashValue = hashValue; 
     this.showdownValue = showdownValue; 
    } 
    @Override 
    public int compareTo(ShowdownSingleValueVO o) { 
     return this.hashValue - o.hashValue; 
    } 
} 

正如你所看到的,目標是讓這些值按其hashValue屬性排序。

任何想法/暗示我做錯了將不勝感激!

感謝, 托馬斯

回答

5

最有可能你正在運行到一個int溢出。由於哈希碼的大小可以是任意大的,因此可以想象,對於某些值對來說,相減會溢出,當減去兩個負數時產生正數。

更換減法與implementation from Integer來解決這個問題:

public int compareTo(ShowdownSingleValueVO o) { 
    return Integer.compare(this.hashValue, o.hashValue); 
} 
相關問題