2012-08-30 60 views
2

我第一次做這樣:Collections.sort VS Arrays.sort - 在Java中

List<String> items = new ArrayList<String>(); 

Comparator<items> ignoreLeadingThe = new Comparator<items>() { 
    public int compare(String a, String b) { 
     a = a.replaceAll("(?i(^the\\s+", ""); 
     b = b.replaceAll("(?i(^the\\s+", ""); 
     return a.compareToIgnoreCase(b); 
    } 
}; 

Collections.sort(items, ignoreLeadingThe); 

現在我這樣做:

ItemObject[] io = new ItemObject[items.size()]; 

Comparator<ItemObject> ignoreLeadingThe = new Comparator<ItemObject>() { 
    public int compare(ItemObject a, ItemObject b) { 
     a.name = a.name.replaceAll("(?i(^the\\s+", ""); 
     b.name = b.name.replaceAll("(?i(^the\\s+", ""); 
     return a.name.compareToIgnoreCase(b.name); 
    } 
}; 

Arrays.sort(io, ignoreLeadingThe); 

當我整理了ArrayList向上頂,它正常行事;它相應地忽略了「The」和排序的列表;但實際上並沒有影響列表的輸出。

但是,當我排序規則Array(填充對象而不是字符串)時,底部代碼實際上刪除了「The」。例如,「小丑」將成爲「小丑」。

有沒有人看到這裏出了什麼問題?

+3

你正在覆蓋'a.name'和'b.name'。爲轉換後的名稱聲明單獨的局部變量,並在'compareToIgnoreCase'中使用這些變量。 – oldrinb

+0

你想要寫:'比較器的方法compare(String,String),你可以這樣寫:'String newA = a.name.replaceAll(「(?i(^ the \\ s +」,「」);' – assylias

+0

)明確地從每個字符串中刪除「the」,改變字符串,你可以在該方法中使用臨時字符串,並對臨時字符串進行操作,它應該修復它。 –

回答

4

正如我在my comment指出,

你覆蓋a.nameb.name。爲轉換後的名稱聲明單獨的局部變量並將其用於compareToIgnoreCase中。

...或者只是使用一個大的表達式。所以,嘗試這樣的...

final Comparator<ItemObject> ignoreLeadingThe = new Comparator<ItemObject>() { 

    final Pattern pattern = Pattern.compile("(?i(^the\\s+"); 

    public int compare(final ItemObject a, final ItemObject b) { 
    return pattern.matcher(a.name).replaceAll("") 
     .compareToIgnoreCase(pattern.matcher(b.name).replaceAll("")); 
    } 
}; 
+0

就是這樣,謝謝! – KickingLettuce