加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

奇怪的Groovy / Java String比较行为

发布时间:2020-12-14 16:32:11 所属栏目:大数据 来源:网络整理
导读:请考虑以下脚本: 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): " +
请考虑以下脚本:

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().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读