The comparator interface is equal to the method, so it is always safe not to override Object.equals (Object)

I am currently studying the interface Comparatorand noticed that the documentation for Comparator equals the method, it indicates

Note that it is always safe not to override Object.equals (Object)

enter image description here

I checked the equalsdefault implementation of the method in the classObject

enter image description here

Thus, when using the equalsdefault method , it simply checks to see if two instances point to the same object, because it this == objchecks reference equality.

But what happens if I have two instances Comparator, the result they return is identical, and I want to know if they are equivalent. If I do not override the default method Object equals, then regardless of whether the result they return is equivalent or not, using the Object equalsdefault method will always be returned false. Is it still always safe not to override Object.equals (Object) ?

+4
source share
1 answer

I assume you misinterpreted what java doc says:

this method can return true only if the specified object is also a comparator and imposes the same order as this comparator

true , , , ( )

, true , , :

import java.util.Comparator;

public class TestComparator {
    static class Comparator1 implements Comparator<Integer> {
        @Override
        public int compare(final Integer o1, final Integer o2) {
            return Integer.compare(o1, o2);
        }
    }

    static class Comparator2 implements Comparator<Integer> {
        @Override
        public int compare(final Integer o1, final Integer o2) {
            return Integer.compare(o1, o2);
        }
    }

    public static void main(final String[] args) {
        final Comparator1 c1 = new Comparator1();
        final Comparator1 c11 = new Comparator1();
        final Comparator2 c2 = new Comparator2();

        System.out.println(c1.equals(c1)); // true
        System.out.println(c1.equals(c11)); // false
        System.out.println(c1.equals(c2)); // false
    }
}

true, , false ( )

, doc :

, , .

, , , , .

+3

Source: https://habr.com/ru/post/1696085/


All Articles