我有compareTo我的列表的代码:
public int compareTo(className a)
{
return (this.long1 > a.long1) ? 1 : -1;
}
Run Code Online (Sandbox Code Playgroud)
当我使用时Collections.sort(list),我收到以下错误:Comparison method violates its general contract!
当我将其更改为if (this.long1 >= a.long2),它可以工作,但它没有正确排序.long按顺序排序,然后按顺序排序,然后按顺序排序.使用>=,输出如下所示:
...
2000100
2000101
2000102
1000100
1000101
2000101
2000102
...
Run Code Online (Sandbox Code Playgroud)
现在,重复确实发生了,他们需要正确排序.重复项首先出现或最后出现并不重要,只要它们按顺序正确分组,如下所示:
...
2000100
2000101
2000101
2000102
2000102
1000100
1000101
...
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?谢谢.
UPDATE
该列表仍然按顺序排序,并提供以下所有建议.这是因为它是一个List<Class> list = new ArrayList<Class>();?我无法使用C#中常用的东西:List<Class> list = new List<Class>().
当两个数字相等时你应该返回0,或者只使用Long.compare:
public int compareTo(className a)
{
return Long.compare(this.long1,a.long1);
}
Run Code Online (Sandbox Code Playgroud)