String comparison with EqualsVerifier.forExamples

92 views
Skip to first unread message

xenson

unread,
May 20, 2011, 4:27:54 PM5/20/11
to equalsverifier
I've created a simple test case to see how EqualsVerifier.forExamples
works, and I was surprised by the results. I don't expect this test to
fail. Could you explain what is going on in this scenario.

String s1 = "a";
String s2 = "a";
String s3 = "a";
EqualsVerifier.forExamples(s1, s2, s3).verify();

java.lang.AssertionError: equals throws ArrayIndexOutOfBoundsException
when field value is null.
For more information, go to: http://code.google.com/p/equalsverifier/wiki/ErrorMessages
at nl.jqno.equalsverifier.util.Assert.fail(Assert.java:96)
at
nl.jqno.equalsverifier.EqualsVerifier.handleError(EqualsVerifier.java:
330)
at nl.jqno.equalsverifier.EqualsVerifier.verify(EqualsVerifier.java:
310)


Jan Ouwens

unread,
May 21, 2011, 7:24:59 AM5/21/11
to equalsv...@googlegroups.com
Hi,

Happy to hear you're playing with EqualsVerifier! I hope you like it.

To answer your question: String is just about the worst class to try
EqualsVerifier on :).
It doesn't follow the well-known patterns in order to get maximum
performance. For example, it uses a lazily-initialized cache for a
hashCode, something EqualsVerifier can't really deal with well[1].

EqualsVerifier will modify the content of the fields in a class to see
how it behaves. 99% of the time this works fine, since most equals
methods work in more or less the same way. String's equals, however,
does not, and by changing the contents of String (which is supposed to
be immutable), EqualsVerifier breaks an internal invariant somewhere,
which causes equals to misbehave. Note that the guys who wrote String
really know their stuff, and don't need EqualsVerifier in the first
place :).

BTW, the test would've failed anyway, because forExamples requires
unequal examples. You've not only given three equal examples, but
(because of String internment) three times the same object instance
:).

If you pick another class, outside of the java.lang package,
EqualsVerifier should behave as expected.

Hope this helps!


Regards,
Jan

[1] For an explanation why this is the case, see
http://code.google.com/p/equalsverifier/issues/detail?id=34#c6

Reply all
Reply to author
Forward
0 new messages