Groovy在GStringImpl上使用equals()和==的不同结果 [英] Groovy different results on using equals() and == on a GStringImpl

查看:311
本文介绍了Groovy在GStringImpl上使用equals()和==的不同结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 groovy文档,==仅仅是一个'聪明的'equals(),因为它也避免了NullPointerException。所以,如果对象不为null,==和equals()应该返回相同的值。但是,在执行以下脚本时,我收到了意想不到的结果:

  println$ {'test'}==' test'
println$ {'test'}。equals('test')

我得到的输出是

  true 
false

一个例子可以在找到在这里



这是一个与GStringImpl相关的已知错误还是我错过了什么?

  println $ {'test'}。equals('test')

返回。另一行代码返回预期的结果,所以让我们忘掉它。



总结



 $ {'test'}。equals('test')

调用等于的对象的类型为 GStringImpl ,而'test'类型字符串,所以它们不被认为是相等的。



但为什么?



显然,等于 GStringImpl 当它传递一个包含与这个相同字符的 String 时,它返回true。 Prima facie,这似乎是一个合理的事情。



我猜这不是这样写的原因是因为它会违反 equals 合约,其中声明:


它是对称的:对于任何非空引用值x和y,当且仅当y.equals(x)返回true时,x.equals(y)才返回true。

执行 String.equals(Object other)将始终返回false当传递 GSStringImpl 时,所以如果 GStringImpl.equals(Object other)在传递任何 String ,这将违反对称性要求。


According to the groovy docs, the == is just a 'clever' equals() as it also takes care of avoiding NullPointerException. So, the == and equals() should return the same value if the objects are not null. However, I'm getting unexpected results on executing the following script:

println "${'test'}" == 'test'
println "${'test'}".equals('test')

The output that I'm getting is

true
false

An example of this can be found here.

Is this a known bug related to GStringImpl or something that I'm missing?

解决方案

Nice question, the surprising thing about the code above is that

println "${'test'}".equals('test')

returns false. The other line of code returns the expected result, so let's forget about that.

Summary

"${'test'}".equals('test')

The object that equals is called on is of type GStringImpl whereas 'test' is of type String, so they are not considered equal.

But Why?

Obviously the GStringImpl implementation of equals could have been written such that when it is passed a String that contain the same characters as this, it returns true. Prima facie, this seems like a reasonable thing to do.

I'm guessing that the reason it wasn't written this way is because it would violate the equals contract, which states that:

It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

The implementation of String.equals(Object other) will always return false when passed a GSStringImpl, so if GStringImpl.equals(Object other) returns true when passed any String, it would be in violation of the symmetric requirement.

这篇关于Groovy在GStringImpl上使用equals()和==的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆