Exception when trying to do custom sort using comparable interface

Viewed 258

I am trying to write a custom sort function using comparable interface.

My compareTo function is as follows:

@Override
    public int compareTo(MyClass o) {
        return (int)(this.getTimeInMills() - o.getTimeInMills());
    }

I am getting the following exception when I try to sort a list of myClass objects.

28T15:02:05.60+0530 [APP/PROC/WEB/0] OUT java.lang.IllegalArgumentException: Comparison method violates its general contract!
   2017-11-28T15:02:05.60+0530 [APP/PROC/WEB/0] OUT     at java.util.ComparableTimSort.mergeHi(ComparableTimSort.java:866) ~[?:1.8.0_152]
   2017-11-28T15:02:05.60+0530 [APP/PROC/WEB/0] OUT     at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:483) ~[?:1.8.0_152]
   2017-11-28T15:02:05.60+0530 [APP/PROC/WEB/0] OUT     at java.util.ComparableTimSort.mergeForceCollapse(ComparableTimSort.java:422) ~[?:1.8.0_152]
   2017-11-28T15:02:05.60+0530 [APP/PROC/WEB/0] OUT     at java.util.ComparableTimSort.sort(ComparableTimSort.java:222) ~[?:1.8.0_152]
   2017-11-28T15:02:05.60+0530 [APP/PROC/WEB/0] OUT     at java.util.Arrays.sort(Arrays.java:1312) ~[?:1.8.0_152]
   2017-11-28T15:02:05.60+0530 [APP/PROC/WEB/0] OUT     at java.util.Arrays.sort(Arrays.java:1506) ~[?:1.8.0_152]
   2017-11-28T15:02:05.60+0530 [APP/PROC/WEB/0] OUT     at java.util.ArrayList.sort(ArrayList.java:1462) ~[?:1.8.0_152]
   2017-11-28T15:02:05.60+0530 [APP/PROC/WEB/0] OUT     at java.util.Collections.sort(Collections.java:141) ~[?:1.8.0_152]

Implementation of MyClass

public class MyClass implements Comparable<MyClass>{

    private String title;
    private String description;
    private Long timeInMills;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Long getTimeInMills() {
        return timeInMills;
    }

    public void setTimeInMills(Long timeInMills) {
        this.timeInMills = timeInMills;
    }

    @Override
    public int compareTo(MyClass o) {
        return (int)(this.getTimeInMills() - o.getTimeInMills());
    }

}

I have seen many answers in the previous posts but none of them helped. can someone let me know the issue with my compareTo function.

1 Answers
Related