I am trying to implement equals
method for Java classes Book
and Chapter
in my application. Book
has a set of Chapter
s, while a Chapter
has an associated Book
. The bidirectional association is shown as 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 book field as well. Wouldn't that start an infinite loop? What is the correct way of implementing the equals
method for such bidirectional associations?