0

I was trying to compare the name of two different Objects, but I kept getting exceptions when using the equals() method to compare an item to null. I've tried so many ways, including other.equals(haha), haha.equals(other), etc, but all failed.

public final class ItemImpl implements Item {
  private final String name;

  public ItemImpl(String name) {
    if (name == null) {
      throw new IllegalArgumentException("name cannot be null!");
    }
    this.name = name;
  }

  @Override
  public String getName() {
    return this.name;
  }

  public boolean equals(Object other) {
    Object haha = name;

    return other.toString().equals(haha.toString());
  }

  public String toString() {
    return this.name;
  }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 2
    Please don't vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/), for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed, and thus, any vandalism will be reverted. If you want to know more about deleting a post please see: [How does deleting work?](/help/what-to-do-instead-of-deleting-question). – cigien Sep 26 '21 at 17:52

1 Answers1

3

Call Objects.equals for tolerance of nulls.

Objects.equals(a,b);
does the job for you, in your case you have also to look that the toString method which you call is not on a null reference.
So use:
return other != null && Objects.equals(toString(), other.toString());

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Julian Kreuzer
  • 358
  • 1
  • 9