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.

3
  • 1
    In general, yes, you can just replace Array.sort on an array with Collections.sort on an ArrayList of the same objects that the array contained. However, you haven't shown all of your code, and your description is slightly cryptic. So, please show a small, but complete code example that we could actually compile and run. Commented Apr 15, 2013 at 0:47
  • 2
    As long as you use the same comparator the results should be identical. See this Ideone. Commented Apr 15, 2013 at 1:08
  • @Perception Thanks. That is all I needed to know. Great effort Commented Apr 15, 2013 at 1:45

2 Answers 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);
        }
    };
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.