I am trying to implement equals
method for Java classes Book
and Chapter
in my application. Book
has a set of Chapt
(I'm assuming this is Java) In the Chapter class equals method, you could just compare the book references (that is, using ==, not equals). This only compare references, so it would avoid an infinite loop. However, if you Clone books sometimes, this approach would fail.
An even better way to solve this specific case would be to compare not the books, but their ISBN, since that is an unique identifier for a Book.
In general, it is better to avoid bidirectional dependencies like this. One way is to have one of the two classes implement an interface, so as not to use it directly.