我第一次做這樣: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」。例如,「小丑」將成爲「小丑」。
有沒有人看到這裏出了什麼問題?
你正在覆蓋'a.name'和'b.name'。爲轉換後的名稱聲明單獨的局部變量,並在'compareToIgnoreCase'中使用這些變量。 – oldrinb
你想要寫:'比較器的方法compare(String,String),你可以這樣寫:'String newA = a.name.replaceAll(「(?i(^ the \\ s +」,「」);' – assylias
)明確地從每個字符串中刪除「the」,改變字符串,你可以在該方法中使用臨時字符串,並對臨時字符串進行操作,它應該修復它。 –