.equals() Override 总是返回 false 且参数为 null

发布于 2025-01-11 19:57:43 字数 835 浏览 3 评论 0原文

我正在尝试使用重写的 .equals() 方法创建一个 Book 类。 Book 对象的构造函数是 Book(String 作者, String 标题, Integer 年份)。问题是,每当其中一个参数为 null 时,即使另一本书的参数也为 null,该方法也会返回 false。 Null 应该是一个有效的选项,并且该方法应该检查其他值是否也等于 null。我尝试过更改 if 语句、构造函数,但没有任何效果。请参阅下面我的尝试。

 public boolean equals(Object other) {
        // Your code here
        if (other == this) {
            return true;
        } else if (!(other instanceof Book)) {
            return false;
        }

        Book book2 = (Book) other;

        if ( (this.title.equals(book2.title) || (this.title == book2.title))
                && (this.author.equals(book2.author) || (this.author == book2.author))
                && (this.year.equals(book2.year) || (this.year == book2.year)) ) {
            return true;
        } else {
            return false;
        }
    }

I am trying to create a Book class with an overriding .equals() method. The constructor for Book objects is Book(String author, String title, Integer year). The issue is that whenever one of the parameters is null, the method returns false even if the parameter for the other book is also null. Null should be a valid option and the method should check whether the other value is also equal to null. I've tried changing the if statements, the constructor, nothing works. Please see my attempt below.

 public boolean equals(Object other) {
        // Your code here
        if (other == this) {
            return true;
        } else if (!(other instanceof Book)) {
            return false;
        }

        Book book2 = (Book) other;

        if ( (this.title.equals(book2.title) || (this.title == book2.title))
                && (this.author.equals(book2.author) || (this.author == book2.author))
                && (this.year.equals(book2.year) || (this.year == book2.year)) ) {
            return true;
        } else {
            return false;
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红焚 2025-01-18 19:57:43

正如 @user16320675 在评论中所说,只需用 Objects.equals() 替换 .equals 方法调用即可检查 null 值并修复我的代码。

As @user16320675 said in a comment, simply replacing the .equals method calls with Objects.equals() checks null values and fixes my code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文