具有双向关联的类的equals()方法 [英] equals() method for classes with bidirectional association

查看:229
本文介绍了具有双向关联的类的equals()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为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 Chapters, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆