In the sorting code, it suddenly reports: comparison method vialates its general contract! The reasons are as follows:
In short, it can be understood as follows:
After JDK7, after the implementation of the compatible interface, the following three features should be satisfied:
1. Reflexivity: the comparison result of X and Y is opposite to that of Y and X
2. Transitivity: X > y,y> z. Then x > z。
3. Symmetry: x = y, then the comparison result of X and Z is the same as that of Y and Z
My code is as follows:
xyList.sort((left, right) ->
{
if (x > y)
return -1;
if (x < y)
return 1;
// When equal returns a random
if ((int) (Math.random() * 2) == 1)
return 1;
return -1;
});
Because when it is equal, it will always return a random result instead of a certain result. If it does not satisfy the symmetry of sorting, the above error will be reported