Um, no -- you're trying to make a good point, but it ends up being bad
advice, because you hit it with too big a hammer... I'm glad you
tried, though.

You really MUST use == when == is the right thing -- and must not use
it otherwise. Primitives are just one case. It's important to
understand what == does, and what .equals() does.

As you note, comparing two strings, say, with == simply compares that
they're physically the same object. This isn't very likely to be
useful for strings. Since they're immutable, one string is generally
as good as another, so long as they contain the right characters.

However -- if your question is "if I modify this object reference,
will that affect that object reference?", then equals() is the WRONG
question to ask.

One way to look at it is .equals() asks about equivalence, while ==,
when applied to an object (rather than a primitive) asks about
identity.

Now, it's reasonable to ask whether you should ever have equals()
return true and == return false in any case when identity might
matter.  In general, I would suggest avoiding that, just on the
grounds of potential confusion. equals() implies a type of
equivalence, while if the identity matters (say, because of instance
state not compared in the equals() method, that says they're not fully
equivalent.

But there often is more than one notion of equivalence at work in a
system. For example, equals() may be defined for supporting use as a
key in a hash table, and thus must consider only immutable fields.

And even if they would both return the same answer, it is better to
use == when that is, in fact, what you are asking. Using equal() on a
mutable instance when you care about identity is itself misleading and
confusing.

If you want to capture this in a short phrase, I'd suggest "same
object (==) vs same content (equals())". Where "same content" means
whatever equals() defines it to mean.

On Jan 12, 2:35 pm, H <[email protected]> wrote:
> No worries.
>
> I should probably clarify a bit by saying that you should only really use
> the "==" when comparing primitives. For non primitives (e.g. any Object
> class - basically anything that starts with a capital letter), most of the
> time, you are probably wanting to use .equals.
>
> Remember that the .equals class can be overriden on any class so some
> classes can customise and choose exactly how to test for equality. If you
> use the "==" then you have no choice in how that test is run other than the
> default way which compares the memory references.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to