Marteno Rodia said:
I've defined a class which, of course, silently extends
java.lang.Object, but I've added some my own attributes. Now I want to
be able to compare two objects of my class i.e. to check if they are
identical.
Do I need to write my own equals() method or can I use the
inherited java.lang.Object.equals() method?
The inherited one considers only identity, not content. If you can have two
instances that are completely interchangeable, you should override equals() to
indicate this. And, of course, if you override equals(), you must override
hashCode() to be consistent.
Note that there _IS_ a risk of being too liberal with equality. If two things
compare as equals, then they will replace each other in sets and map keys.
This is often desired, especially if the key fields that determine equality
are final. In the case of mutable objects, though, you often want them _NOT_
to be equal just because they happen to currently be the same. You only want
them equal if they will always be the same, and can literally be interchanged
in a collection without harm.
There are a few patterns to keep this straight:
1) you can define a new method, "equivalent(Object)", that means "currently
the same, but could later change to be different. Then your code can test
for equivalence when you want, but equals() only means "completely
interchangeable for all Collections".
2) you can be careful with using normal collections in some cases, and
Identity collections (IdentityHashMap, for instance) when you need a different
idea of equality. This usually takes more work than #1, and is easier to have
bugs creep in. But it's sometimes necessary if your object model doesn't have
a well-defined permanent equality.
3) create, use, and love immutable objects. Make all fields final, and you
then don't have to worry about two objects that are the same now, but might
later differ.