gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:28:48 25 4
gpt4 key购买 nike

考虑以下脚本:

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) 为假。根据 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.

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

最佳答案

问题在 Groovy GString page 上得到解答.我需要在 GString 上调用 toString()。

关于java - 奇怪的 Groovy/Java 字符串比较行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6326567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com