简体   繁体   English

奇怪的 Groovy / Java 字符串比较行为

[英]Strange Groovy / Java String comparison behavior

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:当与 Groovy 1.8 和 JDK 1.6.0_14 一起运行时,它具有以下 output:

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.两个字符串 "b" 和 "c" 打印相同的字符序列,但 b.equals(c) 为假。 According to JDK 1.6 manual, the equals() function should return:根据 JDK 1.6 手册,equals() function 应该返回:

Compares this string to the specified object.将此字符串与指定的 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.当且仅当参数不是 null 并且是表示与此 object 相同的字符序列的字符串 object 时,结果才为真。

Why does equals() not return the value as documented and demonstrated above?为什么 equals() 不返回上面记录和演示的值? Strangely, compareTo() returns 0!奇怪的是,compareTo() 返回 0!

The problem is answered on the Groovy GString page .该问题在Groovy GString 页面上得到解答。 I need to call toString() on the GString.我需要在 GString 上调用 toString()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM