title: equals() method for classes with bidirectional association
body: <p>I am trying to implement <code>equals</code> method for Java classes <code>Book</code> and <code>Chapter</code> in my application. <code>Book</code> has a set of <code>Chapter</code>s, while a <code>Chapter</code> has an associated <code>Book</code>. The bidirectional association is shown as below:</p>
  
  <pre><code>class Book{
      private String isbn;
      private String name;
      private Date publishDate;
      private Set&lt;Chapter&gt; 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()) ) &amp;&amp; (this.name.equals(book.getName())) &amp;&amp;(this.publishDate.equals(book.getPublishDate())) &amp;&amp;(this.chapters.equals(book.getChapters())) ){
              return true;
          }else{
              return false;
          }
  
      }
  }
  </code></pre>
  
  <p>Now I tried to implement <code>equals</code> for <code>Chapter</code>:</p>
  
  <pre><code>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())) &amp;&amp; (this.noOfPages.intValue()== book.getNoOfPages().intValue())  ){
              return true;
          }else{
              return false;
          }
      }
  
  }
  </code></pre>
  
  <p>Here, I am wondering if I need to compare the book field as well. Wouldn't that start an infinite loop? What is the correct way of implementing the <code>equals</code> method for such bidirectional associations?</p>