I have googled some same question and I know the reason.However the crash happened only once so I come here to ask you what may lead to crash.
Collections.sort(downloadTasks, new Comparator<DownloadTask>() {
@Override
public int compare(DownloadTask lhs, DownloadTask rhs) {
if (lhs == null || rhs == null) return 0;
return (int) (lhs.mTaskInfo.time - rhs.mTaskInfo.time);
}
});
The error is :
java.lang.IllegalArgumentException: Comparison method violates its general contract! at java.util.TimSort.mergeHi(TimSort.java:864) at java.util.TimSort.mergeAt(TimSort.java:481) at java.util.TimSort.mergeCollapse(TimSort.java:406) at java.util.TimSort.sort(TimSort.java:210) at java.util.TimSort.sort(TimSort.java:169) at java.util.Arrays.sort(Arrays.java:2010) at java.util.Collections.sort(Collections.java:1883)
As you see, I compare two objects by their time
member. The time
is long
type.
I think the crash may be from:
- Whether does converting long to int lead to crash?
- if (lhs == null || rhs == null) return 0; But theoretically lhs and rhs neither is null.
EDIT
If lhs
and rhs
can be null , what should I do ?
EDIT For Android
In Android, Long.compare()
requires API 19. You can do this under API 19 :
public static int compare(long lhs, long rhs) {
return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
}