Consider the following script:
def a = new HashSet()
def str1 = "str1"
def str2 = "str2"
def b = "$str1-$str2"
def c = "str1-str2"
println "b: $b"
println "c: $c"
println "b.equals(c): " + (b.equals(c))
println "b == c: " + (b == c)
println "b.compareTo(c): " + (b.compareTo(c))
a.add(b)
println "a.contains(c): " + a.contains(c)
Which has the following output when run with Groovy 1.8 and JDK 1.6.0_14:
b: str1-str2
c: str1-str2
b.equals(c): false
b == c: true
b.compareTo(c): 0
a.contains(c): false
The two strings "b" and "c" print the same sequence of characters yet b.equals(c) is false. According to JDK 1.6 manual, the equals() function should return:
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Why does equals() not return the value as documented and demonstrated above? Strangely, compareTo() returns 0!
Groovy - compareTo() The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers.
Behaviour of == In Java == means equality of primitive types or identity for objects. In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
The problem is answered on the Groovy GString page. I need to call toString() on the GString.
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