class IntegerComparator implements Comparator<Integer>
{
@Override
public int compare(Integer o1, Integer o2) {
if(o1 < o2)
return 1;
else if(o1 > o2)
return -1;
else
return 0;
}
}
It gives the descending order. I know it. I remember it blindly. I dont understand why the implementation has to be like this.
I expect the results to be ascending order. Because in ascending order, the o1 should be always less than o2 if you take any two adjacent elements. But It gives the descending order which I dont expect.
Can someone demystify the logic behind it
Edit:
- When the elements are swapped. Is it when the compare returns 1 ?

Integerclass has a staticcomparemethod, which does exactly what you want. You may also use thecompareToinstance method.Comparator::reversedwill do that for you.