.equals() Override 总是返回 false 且参数为 null
我正在尝试使用重写的 .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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 @user16320675 在评论中所说,只需用
Objects.equals()
替换.equals
方法调用即可检查 null 值并修复我的代码。As @user16320675 said in a comment, simply replacing the
.equals
method calls withObjects.equals()
checks null values and fixes my code.