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!
The problem is answered on the Groovy GString page. I need to call toString() on the GString.