I have a domain model in which I use a few aggregation relations, i.e. an object of class
A contains zero or more objects of class
I use Java for the implementation and I represent such an aggregation as a field of type
A, and a field of type
B. In this way, each object can be the root of an aggregation tree. Classes
B may also contain other shallow fields, i.e. fields of type
String, and so on.
Now I need to define different kinds of equality methods on my model:
- Shallow equality: compare two instances of
Aby comparing its shallow fields only, i.e. leaving out references to other domain objects. In this case, I am only interested to know if two nodes have the same contents.
- Deep equality: compare two instances of
Aby comparing its shallow fields and by recursively comparing its children. In this case, I want to check if two complete trees are equal.
I considered overriding the
equals() methods for class
A but I do not know if this should be the shallow equality or the deep equality method. Once I decide which of the two equality methods is implemented as
A.equals(), I will define the other method with another name. This is an important choice because the
equals() method determines such things as membership in a
So, is one of the two possibilities (shallow versus deep equality) considered a more idiomatic choice for implementing the
equals method in Java?