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

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

问题描述

根据 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()代码>!

Java’s == is actually Groovy’s is() method, and Groovy’s == is a clever 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.

显然,equalsGStringImpl 实现可以这样编写,这样当它传递一个 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.

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.

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() 和 == 的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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