需要编写equals方法来检查一本书是否与另一本书相同,但一本书包含多个值

  • 本文关键字:一本 包含多 是否 方法 equals java equals
  • 更新时间 :
  • 英文 :


下面是我目前的代码,我需要添加到equals方法中,这样当我创建两本书时,只有当两个属性相同时,它们才会相等。希望你们能帮忙。

public class Book {
private String title;
private boolean bound;
Book(String title, boolean bound) {
this.title = title;
this.bound = bound;
}
@Override
public boolean equals(Object obj) {
if ((obj instanceof Book)) {
return true;
}
return false;
}
}

正确的实现是:

@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(!(obj instanceof Book))
return false;
Book other = (Book) obj;
return bound == other.bound && Objects.equals(title, other.title);
}

两种对象属性都受到尊重!

**更新**

为了避免使用instanceof,您应该使用

if(this.getClass() != obj.getClass())
return false;

感谢user16320675的提示!

您就快到了。然而,如果您实际与书籍进行比较,则此处的instanceof将始终为true。以下内容应该有效。

class Book {
private String title;
private boolean bound;
public Book(String title, boolean bound) {
this.title = title;
this.bound = bound;
}
public String getTitle(){
return this.title;
}
public boolean isBound(){
return this.bound;
}
@Override
public boolean equals(Obj obj) {
if(!(obj instanceof Book)){
return false;
}
if (((Book) obj).isBound() == this.isBound() && ((Book) obj).getTitle().equals(this.getTitle())) {
return true;
}
return false;
}
}

现在你可以比较两本书了。

Book b1  = new Book(new String("Title1"), true);
Book b2  = new Book(new String("Title2"), true);
Book b3  = new Book(new String("Title1"), true);
System.out.println(b1.equals(b2)); // Output is false
System.out.println(b1.equals(b3)); // Output is true

最新更新