考虑以下脚本:
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)
使用Groovy 1.8和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
两个字符串“b”和“c”打印相同的字符序列,但b.equals(c)为false。根据JDK 1.6手册,equals()函数应返回:
将此字符串与指定对象进行比较。当且仅当参数不为null并且是一个表示与此对象相同的字符序列的String对象时,结果才为真。
为什么equals()不会返回上面记录和演示的值?奇怪的是,compareTo()返回0!