具有双向关联的类的equals()方法 [英] equals() method for classes with bidirectional association
问题描述
我正在尝试为Java类实现 equals
方法预订
和章
在我的申请中。 Book
有一组章
s,而章
有一个关联的 Book
。双向关联如下所示:
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;
}
}
}
在这里,我想知道我是否还需要比较书籍领域。那不会开始无限循环吗?为这种双向关联实现 equals
方法的正确方法是什么?
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?
推荐答案
只有当他们的ISBN相等时,一本书应该与另一本书相同。因此,只需根据该字段实现本书等。
A book should be equal to another book only if their ISBNs are equal. So implement the book equals only based on that field.
对于本章 - 比较章节编号和拥有 Book
For the chapter - compare the chapter number and the owning Book
这篇关于具有双向关联的类的equals()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!