Java:compareTo没有正确排序

时间:2015-10-27 11:47:18

标签: java sorting

我的列表中有compareTo代码:

public int compareTo(className a) 
{               
    return (this.long1 > a.long1) ? 1 : -1;
}

当我使用Collections.sort(list)时,出现以下错误:Comparison method violates its general contract!

当我将其更改为if (this.long1 >= a.long2)时,它可以正常工作,但不能正确排序。 long按顺序排序,然后按顺序排序,然后按顺序排序。使用>=,输出如下所示:

...
2000100
2000101
2000102
1000100
1000101
2000101
2000102
...

现在,重复发生,并且需要对它们进行正确排序。重复项首先出现或最后出现并不重要,只要它们按顺序正确分组,如下所示:

...
2000100
2000101
2000101
2000102
2000102
1000100
1000101
...

我该如何正确地做到这一点?谢谢。

更新

列表仍然按顺序排序,并提供以下所有建议。这是因为它是List<Class> list = new ArrayList<Class>();吗?我无法使用我曾经使用的C#:List<Class> list = new List<Class>()

3 个答案:

答案 0 :(得分:9)

当两个数字相等时,您应该返回0,或者只使用Long.compare

public int compareTo(className a) 
{               
    return Long.compare(this.long1,a.long1);
}

答案 1 :(得分:4)

return (this.long1 > a.long1) ? 1 : -1;  

如果两个数字相等,则返回-1,而不是0.

return (this.long1 >= a.long1) ? 1 : -1;  

现在1相等,仍然不是0 正确的:

if(this.long1 > a.long1) return 1;
if(this.long1 < a.long1) return -1;
return 0;

答案 2 :(得分:3)

正确的解决方案可以做到这一点:

var CronJob = require('cron').CronJob;
var job = new CronJob('00 00 12 * * 0-6', function() {
  /*
   * Runs every day
   * at 12:00:00 AM.
   */
  }, function () {
    /* This function is executed when the job stops */
  },
  true, /* Start the job right now */
  timeZone /* Time zone of this job. */
);