Until now, my understanding was that ==
is an operator overload for .equals()
. However, I recently discovered that
new Integer(1) == new Long(1) // returns true
whereas
new Integer(1).equals(new Long(1)) // returns false
so I guess ==
is not exactly a shorthand for .equals()
, so how does it determine equality?
In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Groovy has the following types of operators − Arithmetic operators. Relational operators. Logical operators.
Groovy offers three logical operators for boolean expressions: && : logical "and" || : logical "or" ! : logical "not"
==
in Groovy is roughly equivalent to equals()
, however, you'll find it's different from Java when comparing different classes with the same value - if the class is Comparable
. Groovy also does type casting if possible.
If you check out the code, it looks like ultimately compareToWithEqualityCheck()
is executed for ==
.
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