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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With