Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why we need to return 0 when Comparator.compare become equal

I understand that when implement compare method of Comparator interface we need to return

  • +1 if o1 > o2
  • -1 if o1 < o2
  • 0 if o1 == o2

my question is why we need to return 0 when both equal? what is the use case or where it being used? if we considered sorting when o2 greater than to o1 or o2 equal to o1 does not change it place. can anyone come explain practical use case for this?

Java documentation says

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Does this mean return -1 or return 0 has same impact?

zero, or a positive integer

 @Override
    public int compare(Test f1, Test f2) {
        if (f1.getId() > f2.getId()) {
            return 1;
        } else if (f1.getId() < f2.getId()) {
            return -1;
        } else {
            return 0;
        }

    }
like image 268
Derek Noble Avatar asked Oct 28 '25 17:10

Derek Noble


1 Answers

If you return -1 when the two values being compared are equal, compare(f1,f2) and compare(f2,f1) will both return -1. This means that the ordering of your elements will not be consistent. It can break some sorting algorithms.

That's why the general contract of compare requires that:

sign(compare(f1,f2)) = -sign(compare(f2,f1))

which means you must return 0 when the two values are equal.

like image 115
Eran Avatar answered Oct 31 '25 08:10

Eran



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!