Equals () method for bi-directional association classes

I am trying to implement the equals method for the Java Book and Chapter classes in my application. Book has a collection of Chapter s, and a Chapter has an associated Book . Bidirectional association is shown below:

 class Book{ private String isbn; private String name; private Date publishDate; private Set<Chapter> chapters; ... public boolean equals(Object o){ if(o == this){ return true; } if (!(o instanceof Book)){ return false; } Book book = (Book)o; if( (this.isbn.equals(book.getIsbn()) ) && (this.name.equals(book.getName())) &&(this.publishDate.equals(book.getPublishDate())) &&(this.chapters.equals(book.getChapters())) ){ return true; }else{ return false; } } } 

Now I tried to implement equals for Chapter :

 public class Chapter { private String title; private Integer noOfPages; private Book book; ... public boolean equals(Object o){ if(o == this){ return true; } if (!(o instanceof Chapter)){ return false; } Chapter ch = (Chapter)o; if((this.title.equals(book.getTitle())) && (this.noOfPages.intValue()== book.getNoOfPages().intValue()) ){ return true; }else{ return false; } } } 

Here I am wondering if I need to compare the field of the book. Isn't this the beginning of an endless cycle? What is the correct way to implement the equals method for such bi-directional associations?

+6
source share
4 answers

A book should be equal to another book only if their ISBNs are equal. Thus, the implementation of the book is only based on this field.

In Chapter - Compare Chapter Number and Book Owner

+4
source

(I assume this is Java) In the class method of the Chapter class, you can simply compare the references to books (that is, using == rather than equal ones). This only compares the links, so this avoids the endless loop. However, if you sometimes clone books, this approach will fail.

An even better way to solve this particular case is to compare not the books, but their ISBNs, since this is a unique identifier for the book.

In general, it is better to avoid bidirectional dependencies like this. One way is for one of the two classes to implement the interface, so as not to use it directly.

+1
source

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 a partial relationship, for example, with a book and a chapter, the part (chapter) sometimes takes into account the entire (book) when determining equals (). But not the other way around.

It is so clear that the book will not use its chapters to define equals (). The chapter may use the book. It depends on the model.

+1
source

You must select the Book field as an identifier (for example, ISBN). Then, in Chapter equals, you can do something like

 book.getISBN().equals(other.book.getISBN()) 
+1
source

Source: https://habr.com/ru/post/889142/


All Articles