Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Groovy / Java String comparison behavior

Tags:

java

groovy

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!

like image 728
dromodel Avatar asked Jun 13 '11 04:06

dromodel


People also ask

How do I compare values in groovy?

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.

What is == in Groovy?

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.

What does [:] mean in groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]


1 Answers

The problem is answered on the Groovy GString page. I need to call toString() on the GString.

like image 179
dromodel Avatar answered Sep 29 '22 12:09

dromodel