equals() method for classes with bidirectional association

前端 未结 4 1021
时光说笑
时光说笑 2021-01-17 22:06

I am trying to implement equals method for Java classes Book and Chapter in my application. Book has a set of Chapt

相关标签:
4条回答
  • 2021-01-17 22:53

    You have to choose a Book field as a ID (like ISBN). Then, in Chapter equals, you can do a thing like

    book.getISBN().equals(other.book.getISBN())
    
    0 讨论(0)
  • 2021-01-17 22:57

    From a modeling perspective, the chapter is part of the book. So although you have references in both directions, the book is "stronger" than the chapter.

    When you have part-of relationships like with Book and Chapter, the part (Chapter) sometimes takes the whole (Book) into account when defining equals(). But not the other way round.

    So clearly, the book would not use its chapters to define equals(). The chapter might use the book. That depends on the model.

    0 讨论(0)
  • 2021-01-17 23:05

    (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.

    0 讨论(0)
  • 2021-01-17 23:07

    A book should be equal to another book only if their ISBNs are equal. So implement the book equals only based on that field.

    For the chapter - compare the chapter number and the owning Book

    0 讨论(0)
提交回复
热议问题