0

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;
        }
    }
  • yeah, that was part of my attempts to get the null values to work, since i thought the problem might have been that x.equals(null) returns an exception – tragicstudent Mar 05 '22 at 09:07
  • Objects.equals() fixed everything, thank you! I think you have to write an answer formally so I can close the thread – tragicstudent Mar 05 '22 at 09:07
  • @tragicstudent Be careful in using `instanceof` in your `equals()` method, see https://stackoverflow.com/questions/596462/any-reason-to-prefer-getclass-over-instanceof-when-generating-equals – Progman Mar 05 '22 at 09:55

1 Answers1

0

As @user16320675 said in a comment, simply replacing the .equals method calls with Objects.equals() checks null values and fixes my code.