3

I am trying to sort my custom class array-list using Collections.sort by declaring my own anonymous comparator. But the sort is not working as expected.

My code is

Collections.sort(arrlstContacts, new Comparator<Contacts>() {

        public int compare(Contacts lhs, Contacts rhs) {

            int result = lhs.Name.compareTo(rhs.Name);

            if(result > 0)
            {
                return 1;

            }
            else if (result < 0)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    });

The result is not in sorted order.

2
  • 4
    You know you can just use "return lhs.Name.compareTo(rhs.Name)" ? Commented Apr 10, 2012 at 14:58
  • Under which conditions is this not working? Try stepping through with the debugger and/or writing some unit tests. Commented Apr 10, 2012 at 15:00

2 Answers 2

10

Like Adam says, simply do:

Collections.sort(
  arrlstContacts, 
  new Comparator<Contacts>() 
  {
    public int compare(Contacts lhs, Contacts rhs) 
    {
      return lhs.Name.compareTo(rhs.Name);
    }
  }
);

The method String.compareTo performs a lexicographical comparison which your original code is negating. For example the strings number1 and number123 when compared would produce -2 and 2 respectively.

By simply returning 1, 0 or -1 there's a chance (as is happening for you) that the merge part of the merge sort used Collections.sort method is unable to differentiate sufficiently between the strings in the list resulting in a list that isn't alphabetically sorted.

Sign up to request clarification or add additional context in comments.

Comments

7

As indicated by Adam, you can use return (lhs.Name.compareTo(rhs.Name)); likeso:

Collections.sort(arrlstContacts, new Comparator<Contacts>() {
     public int compare(Contacts lhs, Contacts rhs) {
         return (lhs.Name.compareTo(rhs.Name));
     }
});

2 Comments

Might want to cite Adam's comment.
Didn't see that it has been answered already in the comments. Editing... Thanks!

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.