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;
  }
}
1
  • 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, 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?.
    – cigien
    Commented Sep 26, 2021 at 17:52

1 Answer 1

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());

Not the answer you're looking for? Browse other questions tagged or ask your own question.