Search code examples
javaequals

.equals() Override always returns false with null parameters


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

Solution

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