I've created a complex object in Java and I'm comparing it using the equals method.
Is this okay or is it preferred to give the object a name or an id and compare the objects names/ids?
You should use the equals()
method. If you want to make equality a name and/or id comparison, do it inside the equals()
method.
It is the default way that Java determines equality.
Also, take a look at some of the answers for this question: Overriding the java equals() method quirk
There's a relationship between equals()
and hashcode()
. Both of these are used by Collections.
The default equals
inherited from Object#equals()
compares references. In other words it returns true if the 2 objects are identical (same object in memory).
If you want equals to return true if 2 of your objects share the same characteristics, even if they are different objects, then you should override equals and compare these characteristics.
If you override equals, you should also override hashcode.