“比较法违反了它的一般合同!”有人能简单地解释一下吗?为什么这段代码会抛出一个异常,“比较方法违反了它的一般契约!”,以及如何修复它?private int compareParents(Foo s1, Foo s2) {
if (s1.getParent() == s2) return -1;
if (s2.getParent() == s1) return 1;
return 0;}
3 回答

扬帆大鱼
TA贡献1799条经验 获得超9个赞
你的比较器不是传递性的。
A
B
B
C
A > B
B > C
A > C
A
C
A == C
compareParents()
getParent()

青春有我
TA贡献1784条经验 获得超8个赞
if (value < other.value) return -1;else if (value >= other.value) return 1;else return 0;
value >= other.value
value > other.value

撒科打诨
TA贡献1934条经验 获得超2个赞
if ( one.length() == 0 ) { return 1; // empty string sorts last}if ( two.length() == 0 ) { return -1; // empty string sorts last }return one.compareToIgnoreCase( two );
if ( one.length() == 0 ) { if ( two.length() == 0 ) { return 0; // BOth empty - so indicate } return 1; // empty string sorts last}if ( two.length() == 0 ) { return -1; // empty string sorts last }return one.compareToIgnoreCase( two );
添加回答
举报
0/150
提交
取消