Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do equals() and == mean the same in Groovy script?

Tags:

groovy

The code:

    public class Equals {
    public static void main(String[] args) {

        String s1 = new String("java");
        String s2 = new String("java");

        if (s1 == s2) {
            System.out.println("s1 == s2 is TRUE");
        }
        if (s1.equals(s2)) {
            System.out.println("s1.equals(s2) is TRUE");
        }
    }
}

As a Java app the output is:

s1.equals(s2) is TRUE

which is correct, since s1 and s2 actually points to different memory addresses. But in Groovy script as in GroovyConsole, the output is:

s1 == s2 is TRUE
s1.equals(s2) is TRUE

Does anyone know why?

like image 937
José A. Gaeta Mendes Avatar asked Oct 30 '25 05:10

José A. Gaeta Mendes


1 Answers

Sometimes == in Groovy calls the equals method, but this is not always the case. I'll illustrate by example:

class EqualsTest {
    @Override
    boolean equals(Object obj) {
        true
    }
}

assert new EqualsTest() == new EqualsTest()

The assertion passes, so the theory appears to stand up. However in the following example the assertion fails

class EqualsTest implements Comparable<EqualsTest> {
    @Override
    int compareTo(EqualsTest other) {
        1
    }
    @Override
    boolean equals(Object obj) {
        true
    }
}

assert new EqualsTest() == new EqualsTest() // FAILS!

As stated in Operator Overloading, the test of equality is based on the result of compareTo if the class implements Comparable, but otherwise it's based on equals.

a == b | a.equals(b) or a.compareTo(b) == 0
The == operator doesn't always exactly match the .equals() method. You can think of them as equivalent in most situations. In situations where two objects might be thought "equal" via normal Groovy "coercion" mechanisms, the == operator will report them as equal; the .equals() method will not do so if doing so would break the normal rules Java has around the equals method.

like image 88
Dónal Avatar answered Nov 02 '25 23:11

Dónal