Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: compareTo not sorting correctly [duplicate]

Tags:

java

sorting

I have this compareTo code for my list:

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

When I use Collections.sort(list), I get the following error: Comparison method violates its general contract!

When I change it to if (this.long1 >= a.long2), it works, but it does not sort properly. The longs are sorted in order, then out of order, then in order. Using >=, the output looks like this:

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

Now, duplicates do happen, and they need to be sorted correctly. It doesn't matter if the duplicates appear first or last, as long as they're properly grouped in order, like so:

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

How would I do this properly? Thank you.

UPDATE

The list is still being sorted out of order with all of the below suggestions. Is this because it's a List<Class> list = new ArrayList<Class>();? I can't use what I'm used to from C#: List<Class> list = new List<Class>().

like image 447
Mark Buffalo Avatar asked Dec 04 '25 17:12

Mark Buffalo


2 Answers

You should return 0 when the two numbers are equal, or just use Long.compare :

public int compareTo(className a) 
{               
    return Long.compare(this.long1,a.long1);
}
like image 110
Eran Avatar answered Dec 06 '25 09:12

Eran


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

If both numbers are equal, this returns -1, not 0.

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

Now 1 is equal, still not 0.
Correct:

if(this.long1 > a.long1) return 1;
if(this.long1 < a.long1) return -1;
return 0;
like image 25
deviantfan Avatar answered Dec 06 '25 10:12

deviantfan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!