-1

I would like to compare my contacts to get an alphabetical order but I have this error :

 java.lang.IllegalArgumentException: Comparison method violates its general contract!

This happen when I call :

Collections.sort(aVoid, new CustomComparator());

This is my CustomComparator :

public class CustomComparator implements Comparator<ContactItems> {
        @Override
        public int compare(ContactItems o1, ContactItems o2) {
            if (o1.getName() == null || o2.getName() == null)
                return 0;
            else
                return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
        }
    }

My aVoid array is the result of the method @onPostExecute(List<ContactItems> aVoid) of the class AsyncTaskGetContacts extends AsyncTask<Void, Void, List<ContactItems>>

Jéwôm'
  • 3,753
  • 5
  • 40
  • 73

1 Answers1

5

Consider three values, A, B, and C. Let's say A's name is null, while B and C's names are non-null and are different.

In your comparator, compare(A, B) will return 0. And compare(A, C) will return 0. According to the general contract of comparators, if A==B and A==C, then B==C. But that is not true for your data set. This means there is an error in your compare method.

You need a better method for handling nulls. Probably something like

public int compare(...) {
    if (o1.getName() == null && o2.getName() == null) {
        return 0;
    } else if (o1.getName() == null) {
        return 1;
    } else if (o2.getName() == null) {
        return -1;
    } else {
        return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
    }
}
Ben P.
  • 52,661
  • 6
  • 95
  • 123