3

I had this:

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

Array.sort(MyItemArrayOfObjects, ignoreLeadingThe);

I stopped using Arrays and am now using ArrayList. So when I do this:

Collections.sort(MyItemArrayListOfObjects, ignoreLeadingThe);

I can't even figure out the pattern that it is now sorting by. Can I do a clean switch like this? (It is entirely possible I broke this with something not mentioned above, if this is right, then that's all I need to know)

Note: Originally, with the Arrays I was simply trying to alphabetize a list and ignore the leading "The". It's for an Android app. Each List row Item data was wrapped in an Object that I am passing to an ArrayAdapter. I simply wanted to take an ArrayList inside that object and alphabetize it. So essentially, it's an ArrayList with a few ArrayList inside it.


Your comparator looks good

The bad news is that it does not cache the resulting strings. So your sorting will create o(N*log(N)) Pattern's, Matcher's and String's objects not talking about the fact creation of some of them is not super fast.

UPD

It's advisable to use @Override on the methods you implement for interfaces and override in subclasses.

4

2 回答 2

1

It would work perfectly well for Collections.sort, I only suggest to improve the Comparator

    Comparator<Item> ignoreLeadingThe = new Comparator<Item>() {
        Pattern pattern = Pattern.compile("(?i)^the\\s+");
        public int compare(Item a, Item b) {
            String newA = pattern.matcher(a.name).replaceAll("");
            String newB = pattern.matcher(b.name).replaceAll("");
            return newA.compareToIgnoreCase(newB);
        }
    };
于 2013-04-15T03:38:15.563 回答
1

你的比较器看起来不错

坏消息是它不会缓存结果字符串。因此,您的排序将创建o(N*log(N))Pattern's、Matcher's 和 String's 对象,而不是谈论其中一些对象的创建速度不是很快的事实。

UPD

建议在为接口实现的方法上使用 @Override 并在子类中覆盖。

于 2013-04-15T00:48:34.927 回答