当我尝试订购联系人时,比较方法违反了其一般合同

Jéw*_*ôm' -1 java android

我想比较我的联系人以获得字母顺序,但我有这个错误:

 java.lang.IllegalArgumentException: Comparison method violates its general contract!
Run Code Online (Sandbox Code Playgroud)

当我打电话时发生这种情况

Collections.sort(aVoid, new CustomComparator());
Run Code Online (Sandbox Code Playgroud)

这是我的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());
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的aVoid数组是@onPostExecute(List<ContactItems> aVoid)类的方法的结果AsyncTaskGetContacts extends AsyncTask<Void, Void, List<ContactItems>>

Ben*_* P. 5

考虑三个值A,BC.让我们说A的名字为空,而BC的名字都是非空并且是不同的.

在你的比较器中,compare(A, B)将返回0. compare(A, C)并将返回0.根据比较器的一般合同,如果A == B和A == C,则B == C. 但是对于您的数据集来说并非如此.这意味着您的compare方法中存在错误.

您需要一个更好的方法来处理空值.可能是类似的东西

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());
    }
}
Run Code Online (Sandbox Code Playgroud)