2012-10-22 87 views
0

我正在嘗試基於每個對象內的長存在的值對ArrayList進行排序。在遍歷互聯網的各種例子後,我提出了下面的代碼,但它不按照需要進行排序(它似乎截斷了對象的部分)。基於Long的值對ArrayList排序

public static Comparator<Customer> compareSIN = 
     new Comparator<Customer>() { 
      public int compare(Customer cust1, Customer other) { 
       String sin1 = "" + cust1.sin; 
       String sin2 = "" + other.sin; 
       return sin1.compareTo(sin2); 
      } 
     }; 

請告訴我什麼我做在代碼的第一個片段,它阻止我正確排序的對象丟失。

謝謝!

回答

3

從標題我假設Customer.sinlong - 問題是你試圖比較他們作爲String s而不是他們的數值。

(例如:10000是按字典順序較小然後2 - 因此使用String這兒被故障)

應使用Long.compare()(假設的Java 7):

public static Comparator<Customer> compareSIN = 
     new Comparator<Customer>() { 
      public int compare(Customer cust1, Customer other) { 
       return Long.compare(cust1.sin,other.sin); 
      } 
     }; 
+0

謝謝,請您澄清一下Long.compare()的語法是什麼? – n0shadow

+0

爲什麼在一個簡單的減法中使用Long.compare()?我很好奇。 –

+1

@mCode:當然,請參閱編輯 – amit

2

您實際上並不需要在您自己的compareTo()方法中使用compareTo()方法。

與狀態相比較,如果它們相等,則負數必須返回0,負數或正數則爲非平等。

因此,您可以通過返回從另一箇中減去的長度來比較兩個長整數。

public int compare(Customer cust1, Customer other) { 
      return cust1.sin - other.sin; 
} 

這將作爲你可以看到,返回0,如果他們是平等的,如果負other.sin大於cust1.sin和正面的,如果cust1.sin大於等。罪惡

+0

我想他想比較他們作爲字符串...如果我沒有錯 – amphibient

+0

我認爲他轉換爲字符串,因爲它有一個compareTo方法可用。從他的頭銜和描述他想比較長期價值。什麼會比較字符串表示實現? –

+0

沒有什麼我的口味,但我認爲他轉換爲字符串在某種目的 – amphibient

0

你比較String!而非long s。

因此,假設您想比較:「10」和「5」,結果將是「10」 <「5」,而以爲你與long工作,你希望得到10> 5 ...

這可以解釋您的問題。