How to avoid null exception when using equals() method in Java

Heavenguard.01

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to avoid null excpetion when using equals()method in java

How to avoid null pointer exception using SpEL

How to avoid null warning when using @NotNull and checking for null in another method before method call?

How to avoid lots of checks for null when using get() on a Java Collection?

how to avoid arraysoutofbound exception when using ||

How to avoid null in Java method chain

How to avoid if statements with equals when using enum type?

How to avoid redundant method calls when checking the result first for null?

How to avoid using null?

Getting Null Pointer Exception when using isEmpty() method

how equals method works in java

How to override equals method in Java

Overwritten equals() method requires null check? (java)

Null Pointer Exception When Checking If SharedPrefs Equals Null

How to avoid typecasting to subclass when using null object pattern

How to avoid null values when using Outlay::all()

How to avoid the ExpressionChanged error, when using a method to set [ngClass]?

How to avoid empty value when using getValueAt() method?

How to avoid mutations when using the sub() method in regex?

How to avoid the "unused param" warning when overriding a method in java 1.4?

Java Skip null object when returning with .equals()

java equals. method error when debug

Behavior at Runtime when Overloading the Equals Method in Java

How to avoid Method Overloading in Java to avoid duplicates?

access exception when invoking method of an anonymous class using java reflection

Scala how to avoid using null?

How to avoid Null reference exception when datagrid rows are not visible within grid?

How to avoid null checking in Java?

How equals method behaves when overloaded?