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?
source share