Home > Back-end >  Need to write a equals-method to check if a book is the same as another book but one book contains m
Need to write a equals-method to check if a book is the same as another book but one book contains m

Time:07-16

Below is my code at this moment, I need to add to the equals method so when I create a two books they will only be equal if both of the attributes are the same. Hopefully you guys can help.

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;
    }
}

CodePudding user response:

The correct implementation would be:

@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);
}

Both object properties are respected!

** Update **

To avoid using instanceof you should use

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

Thanks user16320675 for the hint!

CodePudding user response:

You are almost there. However, the instanceof will always be true here if you are actually comparing to books. The below should work.

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;
     }
}

Now you can compare two books.

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

  • Related