问题描述
根据 Groovy 文档,==
只是一个聪明的"equals()
因为它还负责避免 NullPointerException
:
According to the Groovy docs, the ==
is just a "clever" equals()
as it also takes care of avoiding NullPointerException
:
Java的==
其实就是Groovy的is()
方法,而Groovy的==
是一个巧妙的equals()
代码>!
[...]
但是要进行通常的 equals()
比较,您应该更喜欢 Groovy 的 ==
,因为它还可以避免 NullPointerException
,与左侧或右侧是否 null
无关.
But to do the usual equals()
comparison, you should prefer Groovy’s ==
, as it also takes care of avoiding NullPointerException
, independently of whether the left or right is null
or not.
因此,如果对象不为空,==
和 equals()
应该返回相同的值.但是,我在执行以下脚本时得到了意想不到的结果:
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')
我得到的输出是:
true
false
这是一个与 GStringImpl
相关的已知错误还是我遗漏的东西?
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')
返回 false
.另一行代码返回预期结果,所以让我们忘记这一点.
returns false
. The other line of code returns the expected result, so let's forget about that.
"${'test'}".equals('test')
equals
被调用的对象是 GStringImpl
类型,而 'test'
是 String
类型,因此它们不被视为相等.
The object that equals
is called on is of type GStringImpl
whereas 'test'
is of type String
, so they are not considered equal.
显然,equals
的 GStringImpl
实现可以这样编写,这样当它传递一个 String
时,它包含与 this
,它返回真.表面上看,这似乎是一个合理的做法.
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.
我猜它不是这样写的原因是因为它违反了 equals
约定,其中规定:
I'm guessing that the reason it wasn't written this way is because it would violate the equals
contract, which states that:
它是对称的:对于任何非空引用值 x 和 y,当且仅当 y.equals(x) 返回 true 时,x.equals(y) 才应返回 true.
String.equals(Object other)
的实现在传递一个GSStringImpl
时总是会返回false,所以如果GStringImpl.equals(Object other)
code>在传递任何String
时返回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() 和 == 的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!