Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

operator overloading - Groovy different results on using equals() and == on a GStringImpl

According to the Groovy docs, the == is just a "clever" equals() as it also takes care of avoiding NullPointerException:

Java’s == is actually Groovy’s is() method, and Groovy’s == is a clever equals()!

[...]

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...