buildin compareTo:比较方法违反了其总合同

时间:2016-07-25 10:57:36

标签: java sorting collections

我目前正在努力在Java中对Collection进行排序。我收到错误消息'比较方法违反了其一般合同'。我也理解这个错误信息,但我(大多数时候)使用Long类型的buildin compareTo-Method。所以我不知道,在这种情况下,排序方法仍然违反了合同。这是我的代码:

@Override
public int compareTo(DataAge another) {
    if(this == null || another == null)
        return 0;

    Long a = new Long(this.getAge());
    Long b = new Long(another.getAge());
    return a.compareTo(b);
}

这里有错误:

Java exception occurred:
java.lang.IllegalArgumentException: Comparison method violates its general contract!

at java.util.ComparableTimSort.mergeLo(Unknown Source)

at java.util.ComparableTimSort.mergeAt(Unknown Source)

at java.util.ComparableTimSort.mergeCollapse(Unknown Source)

at java.util.ComparableTimSort.sort(Unknown Source)

at java.util.ComparableTimSort.sort(Unknown Source)

at java.util.Arrays.sort(Unknown Source)

at java.util.Collections.sort(Unknown Source)

at dd.GMAAnalyzer.sortData(Analyzer.java:158)

2 个答案:

答案 0 :(得分:5)

假设允许null s,方法的逻辑是不正确的,因为null比较等于任何东西。这是错误的,因为它会比较等于多个不相等的东西,从而打破传递性。

要解决此问题,请确定null s应排在前面还是排在其他数字后面,然后添加单独的null比较(this不能等于{{1} ,所以你不需要比较它。)

null

答案 1 :(得分:1)

来自Comparable的Javadoc:

  

请注意, shirt.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN){ shirt.startAnimation(animationFadeIn); shirt.setImageResource(R.drawable.shirtactive); return true; } else if(event.getAction() == MotionEvent.ACTION_UP){ shirt.startAnimation(animationFadeOut); shirt.setImageResource(R.drawable.shirt); return true; } return false; } }); 不是任何类的实例,即使null返回false,e.compareTo(null)也应该抛出NullPointerException

此外,您无需创建e.equals(null)个实例:

Long