.equals()Override总是使用null参数返回false



我正在尝试创建一个具有重写.equals((方法的Book类。Book对象的构造函数是Book(String author,String title,Integer year(。问题是,只要其中一个参数为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;
}
}

正如@user16320675在一条评论中所说,简单地用Objects.equals()替换.equals方法调用就会检查空值并修复我的代码。

最新更新