// Problem with StringBuffer.equals or StringBuilder.equals
StringBuffer sb = new StringBuffer( 10 );
sb.append( "something" );
if ( sb.equals( "something" ) )
{
// this won't print, as you might expect
System.out.println( "match" );
}
// Instead you must write:
if ( sb.toString().equals( "something" ) )
{
// then it will print
System.out.println( "match" );
}
The problem is StringBuffer.equals checks if two references point to
the same StringBuffer, something you almost never want to do.
StringBuilder has the same gotcha.
--
Roedy Green Canadian Mind Products
http://mindprod.com
The future has already happened, it just isn�t evenly distributed.
~ William Gibson (born: 1948-03-17 age: 61)
Most classes that aren't "String" will have an equals method which
return false when you pass in a String.
Integer foo = Integer.valueOf("100");
if (foo.equals("100")) {
// won't match
System.out.println("match");
}
It may seem like StringBuffer and StringBuilder could consider a special
case, but the problem is that it wouldn't be reflexive
(sb.equals(string) does not imply string.equals(sb))
It might make sense to have an extra method on String, StringBuilder,
StringBuffer:
public boolean matches(CharSequence cs);
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
Actually I tend to think objects almost never equal if not collections
or same-class or some special case.
I'd completely expect StringBuffer and String to never be equals, even
if that forces an otherwise unnecessary toString() call for some
practical use cases.
I'd think it is hardly a gotcha, when dealing a lot with equals() logic.
More to the point, I'd think the gotcha's with equals() apply to a lot
more cases. Better to just read its JavaDoc.
--
Mayeul
>
>I'd think it is hardly a gotcha, when dealing a lot with equals() logic.
>More to the point, I'd think the gotcha's with equals() apply to a lot
>more cases. Better to just read its JavaDoc.
In Java, once you understand the principles, nearly all the gotchas
disappear. But newbies can't do that yet, and old timers don't always
think everything through. A gotcha is not necessarily a flaw in the
language, merely something that can be tripped over.
That's not a "gotcha;" that's "job security!"
--
Eric Sosman
eso...@ieee-dot-org.invalid
Roedy Green wrote:
> In Java, once you understand the principles, nearly all the gotchas
> disappear. But newbies can't do that yet, and old timers don't always
> think everything through. A gotcha is not necessarily a flaw in the
> language, merely something that can be tripped over.
>
Both the newbies and old-timers you describe will benefit from
Mayeul's advice.
The original code that compared 'StringBuilder' to 'String' with
'equals()' but no 'toString()' call ran afoul of some pretty basic
Java stuff, the kind you'd expect to be covered in the first week or
two of learning the language. The 'equals()' method compares 'true'
only for arguments of the same (or rarely, compatible) type. The
'equals()' method defaults to object identity, not value equality.
Can the mistake really be called a 'gotcha' when it's that
fundamental?
That's like calling it a "gotcha" that the value seen after the
postincrement operator ('i++') is the value before incrementing.
Yeah, the operator did what it's supposed to, just like 'equals()' did
what it was supposed to. Gotcha!
--
Lew
>
> That's not a "gotcha;" that's "job security!"
that could explain why old timers usually want any gotcha left as is.
For a start from a OO point of view this is an heresy.
Not every "modelable" OO entity needs the concept
of equality, far from it actually.
Then there's the fact that what equals() tries to
grasp simply cannot be made to work in quite some
cases. Actually, in most cases that are about OO
and not about using Java as a procedural language
(granted, equals() works fine when you use Java as a
procedural language and use objects as some kind of
glofiried C structure to put them in Java's generified
Collections classes).
But as soon as you try to model real OO hierarchies,
you're stuck if you think for one second that equals()
like most Java programmers use it as any utility at all.
Joshua Bloch talks about it in Effective Java and
calls refers to that equals() shortcoming as a a
"fundamental problem".
The almighty Tony Morris who used to post here as
'dibblego' many moons ago (ex-IBM JVM engineer and
by far the most knowledgeable person to ever have
posted in this group) and who's now part of the Scala
fame had quite some very interesting things to say
on the subject.
A recent article (2009) on the subject by the author
of Scala:
http://www.artima.com/lejava/articles/equality.html
The only 'workaround' requires to violate the LSP and to
define a "canEqual" method for all your objects.
Fun uh?
Note that the problem with setters in the example in
the article linked to is, like the circle/ellipsis 'problem',
is *not* an OO problem at all but a problem that has to do
with mutability. There are OO languages that do no support
mutability and hence are immune to the circle/ellipsis
problem.
Gosling's brainfarts whoreshippin' ;) > /dev/null
"Heresy" is an objection to religious dogma on the basis of reason,
and is an accusation leveled by those who have no rationale for their
canon beyond a dictatorial need to control others' thinking.
Properly engaged, an "OO point of view" is not religious dogma, nor is
it supposed to repress rational thinking. Therefore nothing in
programming can be considered "heresy" from that point of view, unless
one is misusing object orientation as a dogma.
Misrepresentation of Josh Bloch's advice does not improve your point.
> Not every "modelable" OO entity needs the concept
> of equality, far from it actually.
>
From the context, one must conclude from this that you refer to value
equality. The default behavior of 'equals' is reference identity,
i.e., the same as the '==' operator. All programming, "OO" or not,
"modelable" (quotes in original) entity or not, needs this. Actually.
> Then there's the fact that what equals() tries to
> grasp simply cannot be made to work in quite some
Huh? What do you mean by "what equals() tries to grasp"? Methods
don't try to "grasp" anything. What are you actually trying to say?
Seriously, I don't know what you mean by this. What is it that you
are saying "equals() tries to grasp"? What 'equals()' actually does
work in all cases.
> cases. Actually, in most cases that are about OO
> and not about using Java as a procedural language
More religion here.
> (granted, equals() works fine when you use Java as a
> procedural language and use objects as some kind of
> glofiried C structure to put them in Java's generified
> Collections classes).
>
Your language is evocative, but your point is obscure. 'equals()'
works just fine everywhere in Java. Could you be precise about what
you claim does not work, what you mean by "real OO hierarchies" ...
> But as soon as you try to model real OO hierarchies,
Not a real Scotsman, eh?
> you're stuck if you think for one second that equals()
> like most Java programmers use it as any utility at all.
>
You say "like most Java programmers use it". How is that, and what
objective statistics do you have to show that most Java programmers
use it that way, and what exactly does it lack in utility?
From my own observation and the body of work of thousands or millions
of Java programmers, it seems that 'equals()' has tremendous utility.
> Joshua Bloch talks about it in Effective Java and
> calls refers to that equals() shortcoming as a a
> "fundamental problem".
>
What "equals() shortcoming"? Is this in /Effective Java/ or some
article somewhere? Are you referring to the difficulty of using
'equals()' in a subclass-to-parent class comparison?
> The almighty Tony Morris who used to post here as
> 'dibblego' many moons ago (ex-IBM JVM engineer and
> by far the most knowledgeable person to ever have
> posted in this group) and who's now part of the Scala
> fame had quite some very interesting things to say
> on the subject.
>
> A recent article (2009) on the subject by the author
> of Scala:
>
> http://www.artima.com/lejava/articles/equality.html
>
> The only 'workaround' requires to violate the LSP and to
> define a "canEqual" method for all your objects.
>
What that article describes is a problem with any method or process
that is improperly or incompletely applied, or else adapted to
situations for which it is not designed. In summary, the article
states that if you use 'equals()' wrong, e.g., not in conjunction with
a consistently-defined 'hashCode()', that you will get incorrect or
surprising results. Now tell me, in what area of programming will
using a method or technique wrong be a good thing?
> Note that the problem with setters in the example in
> the article linked to is, like the circle/ellipsis 'problem',
> is *not* an OO problem at all but a problem that has to do
> with mutability. There are OO languages that do no support
> mutability and hence are immune to the circle/ellipsis
> problem.
>
Yet for some reason the languages that do support mutability are far
more widespread and utile.
Your entire diatribe could have been shortened to the link to the
article and conveyed the exact same amount of actual information,
actually. It was a good article; thanks for the link.
--
Lew
heh heh heh - as an 'old-timer' I'd have to say my concern hasn't been
so much "equals()" but whether the outcome is true or false...
Since I must be an 'old-timer' you must be one I would address 'listen,
sonny'
> For a start from a OO point of view this is an heresy. [...]
(...from *an* OO point...)
Are you by any chance Catholic? Those guys just love to toss around
words like "heresy" - as a matter of fact I *think* they invented the
word back in the dark ages.
AL (residing in procedural purgatory)
:) :) :)
AL wrote:
> (...from *an* OO point...)
Alexandre sports a French email address, so he might not be as conversant with
the niceties of English grammar as those who've been educated in English. Or
he might be, but his thumb slipped and he missed the letter "n" in the
article. Either way, it isn't the sort of grammar lesson one should inflict
on the French.
--
Lew
my apologies - in a gesture widely recognized by that venue, I raise a
white flag...
AL
Please do not take my comment amiss. I'm all in favor of grammatical
correctness, and I've certainly issued my share of corrections and been taken
to task for them. I was actually glad you'd issued the correction - if
Alexandre were listening properly he'd be grateful to you for the assistance
to improve his command of English. It's just that some people get so
namby-pamby when you help them that way.
--
Lew
Grammar humor: <http://tinyurl.com/6rmhgq>
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>