Search code examples
javaandroidcomparable

Android custom sorting using comparable


I have a little problem with this snippet of code:

@Override
public int compareTo(EventResponse o) {
    int compare1 = startTime.compareTo(o.startTime);
    if (compare1 == 0 && o.myProviderId != null && o.providerId != null) {
        return o.providerId.compareTo(o.myProviderId) != 0 ? -1 : 0;
    } else {
        return compare1;
    }
}

I have EventResponse class which i have created that implements Comparable interface, o.myProviderId is ID of currently signed in user (into application) and o.providerId is ID of user that is assigned to particular object (EventResponse). What I need to achieve is if there are two objects with the same startTime to show objects assigned to me first and then objects assigned to some other provider/s.

This code snippet should (and I think it did in the past) do the trick but I get error message stating: "Comparison method violates its general contract".

Please help!


Solution

  • The violation of the contract often means that the comparator is not providing the correct or consistent value when comparing objects.

    For example :

    if (compare1 == 0 && o.myProviderId != null && o.providerId != null) {
        return o.providerId.compareTo(o.myProviderId) != 0 ? -1 : 0;
    }
    

    So, what happens when o.providerId.compareTo(o.myProviderId) gives you 1 or -1. In both scenario you are going to return -1 isn't it ?

    Instead, why not simply return what gets return from compareTo ?

    if (compare1 == 0 && o.myProviderId != null && o.providerId != null) {
        return o.providerId.compareTo(o.myProviderId);
    }