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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6326567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:23:18  来源:igfitidea点击:

Strange Groovy / Java String comparison behavior

javagroovy

提问by dromodel

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 运行时具有以下输出:

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:

两个字符串 "b" 和 "c" 打印相同的字符序列,但 b.equals(c) 为假。根据 JDK 1.6 手册,equals() 函数应该返回:

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.

将此字符串与指定的对象进行比较。当且仅当参数不为 null 并且是表示与此对象相同的字符序列的 String 对象时,结果才为真。

Why does equals() not return the value as documented and demonstrated above? Strangely, compareTo() returns 0!

为什么 equals() 不返回上面记录和演示的值?奇怪的是, compareTo() 返回 0!

采纳答案by dromodel

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

该问题在Groovy GString 页面上得到了解答。我需要在 GString 上调用 toString()。