0

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;
    }
}
MWiesner
  • 8,868
  • 11
  • 36
  • 70
LoveFile
  • 3
  • 1

2 Answers2

2

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!

Thilo Schwarz
  • 640
  • 5
  • 24
  • 2
    controversial use of `instanceof` instead of checking for same class - according javadoc of `equals`, it should be symmetric, that is, `x.equals(y)` should return same result as `y.equals(x)` – user16320675 Jul 15 '22 at 17:09
0

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

  • Your equals does not override the equals method of Object – xthe_white_lionx Jul 15 '22 at 16:53
  • 2
    @Benjamin W. - You're almost there. You need "equals(Object o)", not "Book book". See [Thilo Schwarz's](https://stackoverflow.com/a/72997340/421195) implementation below. And "==" is wrong for Java string comparison. Please [Edit] your reply, before somebody marks you down ;) – paulsm4 Jul 15 '22 at 16:57
  • Thanks I edited it to include type check . – Shavk with a Hoon Jul 15 '22 at 17:14