我首先进行了这种排序:
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”。例如,“ clown ”将变成“ clown ”。
有人看出这里出了什么问题吗?
最佳答案
正如我在 my comment 中所述,
You're overwriting
a.name
andb.name
. Declare separate local variables for the transformed names and use those in yourcompareToIgnoreCase
.
...或者只使用一个大的表达式。所以,尝试这样的事情......
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(""));
}
};
关于java - Collections.sort 与 Arrays.sort - Java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12205950/