我是先做这个排序的:
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“。例如,“小丑”,将变成“小丑”。
有没有人看到这里出了什么问题?
发布于 2012-08-31 05:46:11
正如我在my comment中所说的,
你正在覆盖
a.name和b.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(""));
}
};https://stackoverflow.com/questions/12205950
复制相似问题