javaequalsequality

Meaning of Objects.deepEquals method


The question is about static methods Objects.deepEquals class (since Java 7):

public static boolean deepEquals(Object a, Object b) {
    if (a == b)
        return true;
    else if (a == null || b == null)
        return false;
    else
        return Arrays.deepEquals0(a, b);
}

As it said in javadoc of this method:

Returns true if the arguments are deeply equal to each other and false otherwise.

What I do not understand: where is the depth of comparison? As we can see inside its implementation it just does references comparison, and inside Arrays.deepEquals0(a, b) for simple Object and Object arguments it invokes just: eq = e1.equals(e2);. So in what kind of sense two objects are deeply equal?


Solution

  • The comparison would be deep, if you passed Array objects.

    Non-array objects will not be evaluated deeper than what you get with equals .

    So the depth isn't relevant in your case :

    Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.

    Quoted from :

    Object.deepEquals