Java错误:比较方法违反了它的一般契约我看到了很多关于这方面的问题,并试图解决这个问题,但经过一个小时的谷歌和大量的尝试和错误,我仍然无法解决它。我希望你们中的一些人能理解这个问题。我得到的是:java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.ComparableTimSort.mergeHi(ComparableTimSort.java:835)
at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:453)
at java.util.ComparableTimSort.mergeForceCollapse(ComparableTimSort.java:392)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:191)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at java.util.Collections.sort(Collections.java:155)
...这是我的比较器:@Overridepublic int compareTo(Object o) {
if(this == o){
return 0;
}
CollectionItem item = (CollectionItem) o;
Card card1 = CardCache.getInstance().getCard(cardId);
Card card2 = CardCache.getInstance().getCard(item.getCardId());
if (card1.getSet() < card2.getSet()) {
return -1;
} else {
if (card1.getSet() == card2.getSet()) {
if (card1.getRarity() < card2.getRarity()) {
return 1;
} else {
if (card1.getId() == card2.getId()) {
if (cardType > item.getCardType()) {
return 1;
} else {
if (cardType == item.getCardType()) {
return 0;
}
return -1;
}
}
return -1;
}
}
return 1;
}}知道吗?
3 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
A > B
B > C
A
, B
C
: A > C
if (card1.getRarity() < card2.getRarity()) { return 1;
-1
card1.getRarity() > card2.getRarity()
.
if (card1.getId() == card2.getId()) { //...}return -1;
-1
-1
1
if (card1.getSet() > card2.getSet()) { return 1;}if (card1.getSet() < card2.getSet()) { return -1;};if (card1.getRarity() < card2.getRarity()) { return 1;}if (card1.getRarity() > card2.getRarity()) { return -1;}if (card1.getId() > card2.getId()) { return 1;}if (card1.getId() < card2.getId()) { return -1;}return cardType - item.getCardType(); //watch out for overflow!
神不在的星期二
TA贡献1963条经验 获得超6个赞
java.util.Arrays.sort
java.util.Collections.sort
IllegalArgumentException
Comparable
Comparable
java.util.Arrays.useLegacyMergeSort
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
添加回答
举报
0/150
提交
取消