1

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?

Undefined
  • 1,899
  • 6
  • 29
  • 38

2 Answers2

6

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.

Community
  • 1
  • 1
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
3

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.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783