I am trying to write my own sort function using a comparable interface.
My compareTo function looks like this:
@Override
public int compareTo(MyClass o) {
return (int)(this.getTimeInMills() - o.getTimeInMills());
}
I get the following exception when I try to sort the 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]
MyClass implementation
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 saw a lot of answers in previous posts, but none of them helped. someone can tell me a problem with my compareTo function.
source
share