2

我是先做这样的:

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”。例如,“小丑”将变成“小丑”。

有谁看到这里出了什么问题?

4

1 回答 1

4

正如我在评论中所说,

您正在覆盖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(""));
  }
};
于 2012-08-30T21:46:10.557 回答