Groovy 脚本中的 equals() 和 == 意思相同吗?

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

代码:

    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");
        }
    }
}

作为 Java 应用程序,输出为:

s1.equals(s2) is TRUE

这是正确的,因为 s1 和 s2 实际上指向不同的内存地址。但是在 Groovy 脚本中,如在 Groovy 控制台中,输出是:

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

有人知道为什么吗?

是的,这些运算符是相等的。请参阅 groovy 中的 operator overloading== 运算符 转换equals 方法。

有时 Groovy 中的 == 会调用 equals 方法,但并非总是如此。我将举例说明:

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

assert new EqualsTest() == new EqualsTest()

断言通过,理论似乎站得住脚。但是在下面的例子中,断言失败了

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

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

Operator Overloading所述,如果class实现Comparable,则相等性测试基于compareTo的结果,否则基于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.